我注意到以下代码:
> (123[45] = 67) == 67
<- true
> 123[45]
<- undefined
您也可以在浏览器中尝试。
我不明白发生了什么。
123[45]
在第一个赋值指令中被视为数组,并且实际上正确响应下一个测试 == 67
。
但是,当我尝试访问内存位置 123[45]
时,我得到了未定义的结果。
那是什么?
最佳答案
Primitive values不能有属性(这就是它们与对象的区别)。另请参阅Strings are not object then why do they have properties? , Why can't I add properties to a string object in javascript?和 What’s happening in this code with Number objects holding properties and incrementing the number?关于这个主题。
It actually responds rightfully to the next test
== 67
.
不是属性访问,不。只是赋值表达式始终计算其右侧值,无论赋值目标发生什么情况。
您也可以尝试使用实际对象:
var x = {
get p() { console.log("getting"); return 42; },
set p(val) { console.log("setting "+val); }
};
x.p = 2; // setting 2
console.log(x.p); // getting 42
console.log((x.p = 67) == 67); // setting 67 true - no "getting"!
console.log(x.p); // still: getting 42
关于javascript - 这在 JavaScript 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136598/