【问题标题】:Jquery add variable to another variable name dynamicallyJquery动态地将变量添加到另一个变量名
【发布时间】:2015-12-24 08:33:55
【问题描述】:

我定义了三个变量(仅举例)如下:

window.myCirclePlayer_0 = ...
window.myCirclePlayer_1 = ...
window.myCirclePlayer_2 = ...

我的代码中的其他地方(伪代码):

var index = 0 1 or 2; //index can be 0, 1 or 2, we don't know which yet

然后我想将索引添加到窗口变量,以便它调用正确的方法。但这不起作用。这样的事情有可能吗?

window.myCirclePlayer_[index].doMethod();

【问题讨论】:

    标签: jquery variables dynamic


    【解决方案1】:

    您可以使用window['myCirclePlayer_' + index].doMethod(),但您应该考虑另一种方法。当您看到像 foo_1foo_2 这样的变量时,您可能应该使用数组。

    你可以这样做:

    var circlePlayers = [
      ...,
      ...,
      ...
    ];
    

    那么你就可以更自然地使用索引了:

    circlePlayers[index].doMethod();
    

    您还可以添加更多circlePlayerslike:

    circlePlayers.push(...);
    

    我在上面的代码示例中只使用了...,因为那是你使用的。

    【讨论】:

    • 太棒了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 2013-04-28
    • 2013-09-11
    • 2018-05-27
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多