开发者

["var"+1]=someValue - Can something like this be done?

function giveValue(n){
    ["r"+n]=5;
}
giveValue(10);

You get the idea.

The point is that I have a handful of variables with similar name, varying only in a number at the end. Using a switch statement is fine with a few variables a few times, but f开发者_开发知识库or this particular project it is driving me crazy. I know I can do:

var r2="lol";
var someVar=eval("r"+2);
//someVar=="lol"

And I was wondering if I can do something like this but with the dynamic reference to the left of an assignment.

Is it possible?


If you REALLY want to do that, this should work:

function giveValue(n){
    window['r'+n] = 5;
}
giveValue(10);

console.log(r10)

But please, DON'T DO IT!

You really should use arrays!


The best way is to create an array called r:

var r = [];
r[2] = 5;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜