0

Is it possible to use an array variable value as a new variable name in a for-loop (or in other words, can the left-hand side of an equation be determined by a pre-defined value in an iteration)?

for (var i = 0; i < array.length; i++) {
    // we all know this is possible:
    blabla[i] = apple;
    // but I'm wondering if there's a way we can achieve this:
    example(someVar);
}

function example(name) {
   // [name] = banana;
   name = banana;
}

Obviously, the way I'm doing this in the snippet above, the value banana is always getting assigned to the variable name. Not too sure though how I could go about this?

AKG
  • 2,936
  • 5
  • 27
  • 36
  • Please clarify what you actually want to achieve. It's not clear from your example. What would be the point of assigning a random variable (_banana_) to a local variable (_name_) in a function? And what is _someVar_ (you provide zero context whatsoever for _banana_ and _someVar_). – jahroy Jun 24 '13 at 06:22
  • Maybe I should have asked this question differently. Basically what I want is to able to do something like `eval(someVar) = someValue`. Is that possible? @jahroy – AKG Jun 24 '13 at 06:28
  • That doesn't make sense. You should have a variable on the left side of an assignment statement. Looks like you figured it out, though. – jahroy Jun 24 '13 at 18:36

2 Answers2

2

Variables are properties, either of the global object (in a browser: window) or of some other object. So you can do:

for (var i = 0; i < array.length; i++) {
   window[array[i]] = '[something]';
}

or

var someObj = {};
for (var i = 0; i < array.length; i++) {
   someObj[array[i]] = '[something]';
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0
function myVar(val) {
this.value=val;
}

var array=new Array( new myVar(1),new myVar(2),new myVar(3));

for (var i = 0; i < array.length; i++) {
    example(array[i]);
    alert(array[i].value); // now they are 0,0,0
}

function example(name) {
   name.value = 0;
}
Paul Shan
  • 614
  • 2
  • 8
  • 14