简体   繁体   English

这在Javascript中是什么意思?

[英]What does this mean in Javascript?

I got noticed about the following piece of code: 我注意到以下代码:

>  (123[45] = 67) == 67
<- true
>  123[45]
<- undefined

You can try it inside your browser too. 您也可以在浏览器中尝试。

I don't understand what's going on. 我不明白发生了什么。

123[45] is treated like an array in the first assignment instruction and actually responds rightfully to the next test == 67 . 123[45]在第一个赋值指令中被视为数组,并且实际上正确地响应了下一个测试== 67 But then, when I try to access to the memory location 123[45] I got undefined. 但是,当我尝试访问内存位置123[45]我不确定。

What's that? 那是什么?

Primitive values cannot have properties (that's what distinguishes them from objects). 基本值不能具有属性(这就是它们与对象的区别)。 See also Strings are not object then why do they have properties? 另请参见字符串不是对象,那么为什么它们具有属性? , Why can't I add properties to a string object in javascript? 为什么不能在javascript中将属性添加到字符串对象? and What's happening in this code with Number objects holding properties and incrementing the number? 在此代码中,使用Number对象保留属性并递增数字会发生什么情况? on that subject. 关于这个问题。

It actually responds rightfully to the next test == 67 . 实际上,它正确地响应了下一个测试== 67

Not the property access, no. 不是属性访问,否。 It's just that the assignment expression always evaluates to its right hand value, regardless what happens with the assignment target. 只是赋值表达式总是求出其右手值,而不管赋值目标发生什么。

You can try that with an actual object as well: 您也可以尝试使用实际对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM