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

How to pass an integer to create new variable name?

本文关键字:创建 变量名 整数 一个 何传递      更新时间:2023-09-26

我有50个svg动画,分别命名为animation0、animation1、animation 2等。当0到49的整数传递给这个函数时,我想加载它们:

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

它现在不起作用,也许是通过了"whichswiffy"而不是动画10?

有什么想法吗?

"我有50个svg动画,分别命名为animation0、animation1、animation 2等。"

使用全局变量

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

var whichswiffy = window["animation" + value];

使用对象而不是变量

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

var animations = {
    animation0: your first value,
    animation1: your second value,
    /* and so on */
}

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

var whichswiffy = animations["animation" + value];

使用数组而不是变量

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

var animations = [
    your first value,
    your second value,
    /* and so on */
]

然后使用索引。。。

var whichswiffy = animations[value];

如果您的变量是全局变量,则可以执行

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), window[whichswiffy]);