Increment the name of variable

*爱你&永不变心* 提交于 2019-11-27 07:33:09

问题


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);

回答1:


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.




回答2:


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]);
}


来源:https://stackoverflow.com/questions/7730761/increment-the-name-of-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!