我有点惊讶这有效: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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句