我对这有效感到有点惊讶:http://jsfiddle.net/7yfpc1nL/3/
const arr = ['a', 'b'];
const r = arr[[
[0]
]];
console.log(r);
JavaScript 是否将 [[0]] 强制转换为 0?这里发生了什么魔法?
最佳答案
是的,当使用[]
运算符访问对象的属性时,JavaScript将参数强制为字符串,[[0]]
的字符串形式为只是 0
,因此这是访问第零个元素的迂回方式。
举例说明:
const arr = ['a', 'b']
const idx = String([[0]]) // => "0"
arr[idx] // => "a"
我们可以验证参数的字符串形式是否按如下方式使用:
const obj = {
toString: function() {
console.log('OK: called obj.toString()')
return 1
}
}
arr[obj] // => "b"
// OK: called obj.toString()
关于javascript - 使用单个整数数组访问另一个数组中的项目时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956009/