如何传递一个整数来创建新的变量名?

Joe*_*Joe 0 javascript

我有50个名为animation0,animation1,animation2等的svg动画,我想在将0到49的整数传递给此函数时加载它们:

function loadAnimation(value){
    var whichswiffy = "animation" + value;
    var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), whichswiffy);
    stage.start();
}
Run Code Online (Sandbox Code Playgroud)

它现在不起作用,也许它正在传递'哪些'而不是动画10?

有任何想法吗?

小智 5

"我有50个svg动画,名为animation0,animation1,animation2等."

使用全局变量

我认为这意味着你有变量.如果它们是全局变量,则可以将它们作为全局对象的属性进行访问.

var whichswiffy = window["animation" + value];
Run Code Online (Sandbox Code Playgroud)

使用Object而不是变量

但如果它们不是全局变量(或者即使它们是),那么最好将它们存储在Object中......

var animations = {
    animation0: your first value,
    animation1: your second value,
    /* and so on */
}
Run Code Online (Sandbox Code Playgroud)

...然后将它们作为该对象的属性进行访问...

var whichswiffy = animations["animation" + value];
Run Code Online (Sandbox Code Playgroud)

使用数组而不是变量

或者更好,只使用数组,因为唯一的区别是数字...

var animations = [
    your first value,
    your second value,
    /* and so on */
]
Run Code Online (Sandbox Code Playgroud)

那么只需使用索引......

var whichswiffy = animations[value];
Run Code Online (Sandbox Code Playgroud)