Increment the name of variable

前端 未结 2 1144
萌比男神i
萌比男神i 2020-12-11 12:07

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

             


        
相关标签:
2条回答
  • 2020-12-11 12:56

    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.

    0 讨论(0)
  • 2020-12-11 12:59

    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]);
    }
    
    0 讨论(0)
提交回复
热议问题