Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

arrays - JavaScript null and plus (+) operatior

I am trying to understand the core of JavaScript. I know it doesnt have much implementation value. If you dont want to answer, just leave it. However, I will appreciate if you could help to understand the following type coercion while applying addition(+).

1. 
null + null // 0
2.
null + undefined; // NaN
3.
null + NaN; // NaN
4. 
1 + null; //1
5. 
true + null; //1
6. 
true + [null]; //"true"

I know null is an empty or missing object. I will appreciate, if you can explain steps in type coercion or unary(+) operation here. Thanks for reading the question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is covered in 11.6.1 The Addition operator ( + ) - feel free to read it and follow the rules.

The first five cases can be explained by looking at ToNumber:

Value       ToNumber(Value)
---------   ---------------
null        0
undefined   NaN
NaN         NaN
1           1
true        1

And 0 + 0 == 0 (and 1 + 0 == 1), while x + NaN or NaN + x evaluates to NaN. Since every value above is also a primitive, ToPrimitive(x) evaluates to x (where x is not a string) and the "string concatenation clause" was not invoked.

The final case is different in that it results from the ToPrimitive (which ends up calling Array.prototype.toString) on the array which results in a string value. Thus it ends up applying ToString, not ToNumber, and follows as such:

   true + [null]
=> true + ""          // after ToPrimitive([null]) => ""
=> "true" + ""        // after ToString(true) => "true"
=> "true"             // via String Concatenation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...