简体   繁体   中英

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 . But then, when I try to access to the memory location 123[45] I got undefined.

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? and What's happening in this code with Number objects holding properties and incrementing the number? on that subject.

It actually responds rightfully to the next test == 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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