如果我有:
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/