繁体   English   中英

如何定位名称等于变量值的数组?

[英]How do I target an array which's name is equal to a variable's value?

 // here goes random number generator // arrays with info foo1 = ["This is true!", true, false]; foo2 = ["This is false!", false, false]; foo3 = ["This is probably false!", false, false]; foo4 = ["This is probably true!", true, false]; foo5 = ["This might be true!", true, false]; // choosing a random array name fooID = "foo" + randomNumber(1, 5); /* How would I make this work? - alert(<value of fooID>[0]); <value of fooID>[2] = true; */ 

我想做的是选择一个随机数组(都命名为foo__),然后对其进行处理。

也许我什至可以以完全不同的方式定位数组,甚至不需要fooID变量? 我在StackOverflow中环顾四周 ,发现应该使用字典,但我并不知道如何使用字典。

您可以仅使用Array ,因为您的数据是可迭代的,并且需要一个随机数来获取结果。

 function getRandomElement(array) { return array[Math.floor(Math.random() * array.length)] } var foos = [ ["This is true!", true, false], ["This is false!", false, false], ["This is probably false!", false, false], ["This is probably true!", true, false], ["This might be true!", true, false] ], i; for (i = 0; i < 10; i++) { console.log(getRandomElement(foos)[0]); } 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以使用方括号表示法 ,因为变量是全局定义的,因此window[/* array variable identifier */]

 // here goes random number generator // arrays with info foo1 = ["This is true!", true, false]; foo2 = ["This is false!", false, false]; foo3 = ["This is probably false!", false, false]; foo4 = ["This is probably true!", true, false]; foo5 = ["This might be true!", true, false]; // choosing a random array name fooID = window["foo" + 1 /* randomNumber(1, 5) */ ]; console.log(fooID); 

也许我甚至可以以完全不同的方式来定位数组,

 var foo = [ ["This is true!", true, false], ["This is false!", false, false], ["This is probably false!", false, false], ["This is probably true!", true, false], ["This might be true!", true, false] ]; var fooItem = foo[Math.trunc(Math.random()*5)]; console.log(fooItem); 

确实,只需在数组内创建一个数组。

基本上,您可以使用方括号属性表示法来实现所需的目的,因为您可以在属性名称中使用变量或任何其他有效的JS表达式元素。

在您的示例中,foo1到foo6作为变量存在于全局命名空间中,这意味着它们都已附加到浏览器中的window对象。

因此,将要访问的变量的名称存储在变量中,例如可以使用名称accessor ,然后像这样访问相应的变量:

window[accessor]
// here goes random number generator

// arrays with info

foo1 = ["This is true!", true, false];
foo2 = ["This is false!", false, false];
foo3 = ["This is probably false!", false, false];
foo4 = ["This is probably true!", true, false];
foo5 = ["This might be true!", true, false];

// choosing a random array name

fooID = window["foo" + 3 /*randomNumber(1, 5)*/];

/* How would I make this work? -

alert(<value of fooID>[0]);
<value of fooID>[2] = true;

*/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM