1

Possible Duplicate:
javascript - dynamic variables

Can I have something like this is Jquery

for(var i=0;i<10;i++)
{
   var (eval(i+17)) = y;
   y++;
}

I need this because I want to have dynamic variable created on fly any should be able to asign values to it.

Community
  • 1
  • 1
prashiddha
  • 49
  • 2
  • 5
  • ....huh? This question no sense. – cHao Oct 14 '11 at 02:38
  • 1
    Your code isn't making sense to us. You're trying to do `var eval(17)= y;` which turns into `var 17 = y;`. This doesn't make sense and isn't legal javascript. Please clarify what you're really trying to do. – jfriend00 Oct 14 '11 at 02:41

2 Answers2

6

The correct answer here is to use arrays:

var arr = [];
for (var i = 0; i < 10; i++) {
    arr[i + 17] = y;
    y++;
}

If you know your current context, you can create variables in it the same way. Say, for the global (window) scope:

for (var i = 0; i < 10; i++) {
    window[i + 17] = y;
    y++;
}

But that means you're stomping all over your scope with random variable names. Keep them in one array instead.

deceze
  • 510,633
  • 85
  • 743
  • 889
3

Actually, you don't have to use arrays. You can use objects just as well.

var y = 0;
var obj = {};
var arr = [];
for (var i = 0; i < 10; i++) {
    obj[i + 17] = y
    arr[i + 17] = y;
    y++;
}

console.log(obj);
console.log(arr);

The console output would look (expanded) like that:

Object
    17: 0
    18: 1
    19: 2
    20: 3
    21: 4
    22: 5
    23: 6
    24: 7
    25: 8
    26: 9
    __proto__: Object

    [undefined, undefined, undefined, undefined, 
undefined, undefined, undefined, undefined, undefined, 
undefined, undefined, undefined, undefined, undefined, 
undefined, undefined, undefined, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

JSFiddle to play with is here.

The added benefits of using object are:

  • your obj var should be smaller in size than your arr variable, since it won't have "unused indices"
  • You could name your dynamic variable whatever you want, as opposed to array - where it has to be an integer.

The following would work for object and fail to add any variable to array:

var y = 0;
var obj = {};
var arr = [];
for (var i = 0; i < 10; i++) {
    obj['my variable' + (i + 17)] = y
    arr['my variable' + (i + 17)] = y;
    y++;
}

The arr would look like that:

Object
    my variable17: 0
    my variable18: 1
    my variable19: 2
    my variable20: 3
    my variable21: 4
    my variable22: 5
    my variable23: 6
    my variable24: 7
    my variable25: 8
    my variable26: 9
    __proto__: Object

and arr would be empty: []

ZenMaster
  • 12,363
  • 5
  • 36
  • 59
  • +1 for objects, they would indeed be more correct to use for non-sequential or non-numerical keys. – deceze Oct 14 '11 at 04:13