javascript 增加变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7730761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:06:33  来源:igfitidea点击:

Increment the name of variable

javascriptloopsvariablesincrement

提问by user455318

Basically I want to increment the name of the variable. What is the correct syntax to do this?

基本上我想增加变量的名称。执行此操作的正确语法是什么?

for (i=0; i<5; i++) {
    eval("var slider_" + i);

    var slider_+i = function(){
    //some code
}

dojo.addOnLoad(slider_+i);

回答by James Montagne

Why not just use an array?

为什么不直接使用数组?

var slider = [];

for (i=0; i<5; i++) {
    slider[i] = function(){
        //some code
    }

    dojo.addOnLoad(slider[i]);
}


Alternatively, you could access them based on the object they are contained within. Assuming they are global variables (hopefully not):

或者,您可以根据它们包含的对象访问它们。假设它们是全局变量(希望不是):

for (i=0; i<5; i++) {
    window["slider_"+i] = function(){
        //some code
    }

    dojo.addOnLoad(window["slider_"+i]);
}

window["something"]is another way to access a global variable named something.

window["something"]是另一种访问名为 的全局变量的方法something

回答by styrr

The right way to do so is to use an object or array. This should work:

正确的方法是使用对象或数组。这应该有效:

var slider = {}; // object
// var slider = [] ; // array
for (i=0; i<5; i++) {
    slider[i] = function() {
        // some code ...
    }
    dojo.addOnLoad(slider[i]);
}