javascript - 连接字符串时如何引用数组元素?

标签 javascript

如果我有:

var b1 = ["B", "V"];

我可以访问"V"b1[1] ;

为什么以下不起作用:

console.log(("b"+1)[1]);

我在控制台中得到 1。

最佳答案

如果b1是在全局范围内定义的,则可以将其作为窗口对象的成员进行访问:

// When variable is defined in global scope
var b1 = ["B", "V"];
console.log(window['b'+1][1]);

// Inside a function you're stuck with eval.
// You should be really, really careful with eval.
// Most likely you can change your design so you wont need it.
function test() {
  var b2 = ["B", "V"];
  console.log(eval(('b'+1))[1]);
}

test();

// Just to demonstrate that accessing an object's properties
// always works the same way
window['console']['log']('hi');

关于javascript - 连接字符串时如何引用数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42045227/

相关文章:

javascript - 实现常量变量的正确方法是什么?

javascript - 无法读取React中未定义的属性 'forEach'

javascript - 循环多维数组

javascript - 在javascript中使用正则表达式抓取最后一个斜杠后的URL结尾

javascript - 使用reduce javascript将字符串转换为对象

javascript - 如何使用 'javascript' 检索完整的客户信息

javascript - 是否可以在 VSCode 中自动完成相对路径

javascript - 从 div 中删除 google map 对象

javascript - 禁用react-native-autocomplete-input的输入

javascript - 在 JS 中对数组进行排序和过滤