开发者

Dynamic Javascript variable names [duplicate]

This question already has answers here: Closed 10 years ago.

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开发者_StackOverflow中文版 it.


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.


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: []

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜