JavaScript null和plus(+)operatior [英] JavaScript null and plus (+) operatior

查看:159
本文介绍了JavaScript null和plus(+)operatior的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解JavaScript的核心。我知道它没有太大的实施价值。如果你不想回答,那就离开吧。但是,如果您在应用加法(+)时能够帮助理解以下类型强制,我将不胜感激。

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"

我知道null是一个空的或丢失的对象。如果你能解释类型强制或一元(+)操作的步骤,我将不胜感激。感谢您阅读此问题。

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.

推荐答案

这包含在 11.6.1加法运算符(+) - 随意阅读并遵守规则。

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

前五个案例可以是通过查看 ToNumber 来解释:

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

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

0 + 0 == 0 (及 1 + 0 == 1 ),而 x + NaN NaN + x 评估为NaN 。由于上述每个值也都是原始值,因此 ToPrimitive(x) 计算到x(其中x不是字符串),并且未调用字符串连接子句。

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.

最后一种情况不同它来自 ToPrimitive (最终调用 Array.prototype.toString )会产生 string 值。因此它最终应用 ToString ,而不是 ToNumber ,并且如下:

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

这篇关于JavaScript null和plus(+)operatior的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆