问题
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