문제

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 for 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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top