0

I'm trying, but unsuccessfully, to get the value of a variable, where the variable name is dynamic

var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value; 
for (i = 1; i <=5 i++) {
    alert(window["v_"+i+"playerName"]);
}

Is this possible?

8
  • You are trying to alert the string v_1playerName and not the value of the variable. Commented Mar 25, 2016 at 1:18
  • did you try var windowName = "v_"+i+"playerName"; alert(window[windowName]); ? Commented Mar 25, 2016 at 1:18
  • At this point I just want to know the value of the variable. It's in a simple function that as exactly this code, nothing else. Commented Mar 25, 2016 at 1:18
  • @ochi: how would i get the value of the html field like that? Commented Mar 25, 2016 at 1:21
  • 1
    You are trying to address the wrong problem. You can do this with eval, but that's evil (even if you do not have a security issue, it makes your code slower); but what you really should be doing is having either an object or array to hold both of your values. Commented Mar 25, 2016 at 1:22

3 Answers 3

4

A simple thing would be to put the variables in an array and then use the for loop to show them.

var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value; 
var nameArray = [v_1playerName,v_2playerName];
for (var i = 0; i < 5; i++) {
alert(nameArray[i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@PedroSales You could do something like this : code var playerArray = document.querySelectorAll('div.playerElement'); playerArray.forEach(p => alert(p.value);)code
1

Accessing variables through window isn't a great idea.

Just store the values in an object and access them using square notation:

var obj = {
  v_1playerName: 0,
  v_2playerName: 3
}

obj['v_' + 2 + 'playerName']; // 3

Comments

1

If you want to keep named references to things you could use an object.

var playerNames = {};
playerNames['p1'] = document.getElementById("id_1playerName").value;
playerNames['p2'] = document.getElementById("id_2playerName").value;
for (i = 1; i <= 2; i++) {
  // dynamically get access to each value
  alert.log(playerNames['p' + i])
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.