null 在算术表达式中是否被解释为 0,undefined 是否被解释为 NaN?
根据一些测试结果看起来是这样的:
> null + null
0
> 4 + null
4
> undefined + undefined
NaN
> 4 + undefined
NaN
假设这样做安全可靠吗?(如果有文档引用的话那就更好了)。
null 在算术表达式中是否被解释为 0,undefined 是否被解释为 NaN?
根据一些测试结果看起来是这样的:
> null + null
0
> 4 + null
4
> undefined + undefined
NaN
> 4 + undefined
NaN
假设这样做安全可靠吗?(如果有文档引用的话那就更好了)。
ToNumber操作:
Argument Type | Result
--------------+--------
Undefined | NaN
Null | +0
… |
它用于以下“算术”表达式中:
它不被equality运算符使用,所以null == 0是false(而且null !== 0)!
undefined和null分别计算出NaN和+0。请注意,保留HTML标记。
To Number Conversions
╔═══════════════╦════════════════════════════════════════════╗
║ Argument Type ║ Result ║
╠═══════════════╬════════════════════════════════════════════╣
║ Undefined ║ NaN ║
║ ║ ║
║ Null ║ +0 ║
║ ║ ║
║ Boolean ║ The result is 1 if the argument is true. ║
║ ║ The result is +0 if the argument is false. ║
║ ║ ║
║ Number ║ The result equals the input argument (no ║
║ ║ conversion). ║
║ ║ ║
║ String ║ See grammar and note below. ║
║ ║ ║
║ Object ║ Apply the following steps: ║
║ ║ 1. Let primValue be ToPrimitive(input ║
║ ║ argument, hint Number). ║
║ ║ 2. Return ToNumber(primValue). ║
╚═══════════════╩════════════════════════════════════════════╝
+的另一个操作数是字符串,则会调用ToString并执行字符串连接。因此,null + "hello"是字符串"nullhello"。 - Pointy没有类型限制,
null == false == 0
null !== false !== 0
http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN#0_6
话虽如此,null == 0,null + 4 = 4
希望这能帮到你。
false == 0,虽然false和0不相等,但它们都不等于null。你试过了吗? - Bergi
+。 - Pointystring + <thing>是字符串连接,而int + <thing>是整数加法。 - Brian S