0

Is there a way to make the value of a variable the name for another variable? For example, I want the variable name (value_of_i) to be what ever number "i" is during that iteration. The while loop below is not what I'm using it for, it's just to explain what I'm asking.

var i = 1;
while(i<10)
{

var value_of_i = "This loop has ran " + i + "times.";

i++;
}

For the first iteration, "i" is equal to 1 so I would want the variable name to be "1":

var 1 = "This loop has ran " + i + "times.";

And the second interation:

var 2 = "This loop has ran " + i + "times.";
ajodom10
  • 141
  • 1
  • 4
  • 12
  • See this post: http://stackoverflow.com/questions/6084858/javascript-use-variable-as-object-name – gongzhitaao Mar 24 '13 at 18:33
  • how about putting all data in a json object and accessing myVar['wantedIndex'] ? Also, you can try window['yourVariableName'] global array. – Youn Elan Mar 24 '13 at 18:36
  • 1
    fwiw `var 1 = "..."` is not valid. Numbers can't be variable names in javascript. – Ben McCormick Mar 24 '13 at 18:37
  • 3
    @YounElan I think you mean javascript object. JSON refers to a data format and is not part of the official javascript spec. See here: http://stackoverflow.com/questions/6151593/what-is-the-difference-between-an-json-and-array – Ben McCormick Mar 24 '13 at 18:37
  • possible duplicate of [javascript - dynamic variables](http://stackoverflow.com/questions/4385084/javascript-dynamic-variables) and [many, many others](http://stackoverflow.com/search?q=%5Bjavascript%5D+dynamic+variables). – Felix Kling Mar 24 '13 at 18:52

4 Answers4

2

Yes. Using bracket notation (Here is a tutorial in MDN)

Here is a working fiddle

When doing something like containingObject[stringVariable] you are accessing the property in containingObject whose name is the value stored in stringVariable.

// this assumes browser JavaScript where window is the global namespace
// in node.js this would be a little different
var i=0;
while(i<10){ 
   window["counters"+i] = "This is loop has ran " + i + "times.";
   i++;
}
console.log(counters3);

If you'd like you can use this instead of window, however this might fail in strict mode.

Here is the main explanation of how bracket notation works from the MDN link above:

Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;

You can also access properties by using a string value that is stored in a variable:

var propertyName = "make";
myCar[propertyName] = "Ford";

propertyName = "model";
myCar[propertyName] = "Mustang";
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

You can't make a variable name a number, its not a valid name. So var 1="" is invalid.

But to dynamically set the value you can do

var x = "variablenamehere";

window[x] = "variablevaluehere";

Thats the same as

var variablenamehere

except that it will be scoped as a global variable and will be accessible everywhere, rather than being limited to the current function scope.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

Why not store your strings in an array that is indexed by i?

That way you can reference them later efficiently and easily;

var loopI = new Array();

for(var i = 0; i < 10; ++i) {
    loopI[i] = "This loop has ran " + i + "times.";
}
GriffLab
  • 2,076
  • 3
  • 20
  • 21
0

This works:

var o = {};
var d = "dog";
for (var k = 0; k < 5; k += 1) {
    o[d+k] = k*100;
}
console.log(o.dog3);  // 300

This comes closer to doing what you want:

var N = {};
var M = {};
var i = 1;
while(i<10)
{
    N[i] = "This loop ran " + i + " times.";
    // Or, so you can use dot notation later:
    M['OO'+i] = "This loop ran " + i + " times.";
    // Those are capital O's, not zeros. Numbers won't work.
    i++;
}
console.log(N[3]); // This loop ran 3 times.
console.log(M.OO7); // This loop ran 7 times.

The 'OO' notation could cause bewilderment and wasted time for others trying to use your code; but it could also be a source of amusement for them. This reminds me of a chess board after white's first two moves are to bring out a knight and then put it back. The board then seems to show that black moved first, and some people will endlessly insist that the configuration proves there was illegal play unless someone tells them what happened.

David Schalk
  • 110
  • 4