考虑以下代码:
let logged = 1;
let x = {logged} //{logged: 1}
x['logged']; // 1
x['logged']['index']; //undefined
x['logged']['index'] = 0;
x; // {logged: 1}
x['logged']['index']; //undefined
因此,我的问题是:不是吗
x[logged]['index']
正在做类似于1['index']
的事情。不应该它给出了类似cannot index a numeric literal
的东西错误x[logged]['index'] = 0;
,这不会引发任何错误,就好像元素存储在某个地方,但是,这个值存储在哪里?如line 6
所示,x的值仍然是{logged: 1}
。为什么它不抛出错误?为什么x[logged]['index']仍然没有定义
我在nodejs终端上测试了这一点,节点版本为14.16.0
不确定我上面的评论是否真的为您充分说明了这个问题。
我写了一个小程序,它可能有助于可视化所发生的事情。注意,我正在对基元值进行方法查找,而不是常规的属性查找,但这一切都是一样的,可以更好地说明发生了什么。
function captureThis() {
return this
}
(function setUpObjectPrototype() {
if (Object.prototype.captureThis !== undefined) throw new Error("Couldn't set up Object prototype properly.")
Object.prototype.captureThis = captureThis
process.nextTick(() => delete Object.prototype.captureThis)
})()
var number = 1
var thisObject = number.captureThis()
console.log("Is thisObject an object? " + (typeof thisObject == "object"))
console.log("Is number still just a number? " + (typeof number == "number"))
console.log("Is thisObject an instance of Number? " + (thisObject instanceof Number))
// Output
// Is thisObject an object? true
// Is number still just a number? true
// Is thisObject an instance of Number? true
请注意,在任何情况下,数字变量都不会被强制为对象——会创建一个临时对象来包装数字变量中包含的值。这个对象从来没有实际分配给一个变量——除非它像在这个小程序中那样被捕获。
希望这能有所帮助。