Jquery动态地将变量添加到另一个变量名

时间:2015-09-26 18:05:41

标签: jquery variables dynamic

我定义了三个变量(例如),如下所示:

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

我的代码中的其他地方(pseu-code):

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

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

window.myCirclePlayer_[index].doMethod();

1 个答案:

答案 0 :(得分:1)

你可以SELECT id FROM (SELECT *, IF(@prevvalue <> id, @counter:=0, @counter), IF(@counter < counter, @counter:=@counter + 1, NULL) shouldshow, @prevvalue:=id FROM (SELECT table1.*, table2.id t2id, table2.counter FROM table1 JOIN (SELECT COUNT(id) counter, id FROM table2 GROUP BY id) table2 ON (table1.id = table2.id) ORDER BY table1.id) table1, (SELECT @counter:=0, @prevvalue:=NULL) countertable) table1 WHERE shouldshow IS NULL ORDER BY id; 但你应该考虑另一种方法。当您看到window['myCirclePlayer_' + index].doMethod()foo_1等变量时,您可能应该使用数组。

您可以采取以下措施:

foo_2

然后你可以更自然地使用索引:

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

您还可以添加更多circlePlayers[index].doMethod(); ,如:

circlePlayers

我在上面的代码示例中仅使用了circlePlayers.push(...); ,因为这是您使用的内容。