每个人都知道 JavaScript 中两个字符串的基本连接:
> "Hello " + "World!"
'Hello World!'
但是如果我们使用 + +
而不是 +
会发生什么?我刚遇到以下奇怪行为:
> "Hello " + + "World!"
'Hello NaN'
> "Hello " + + ""
'Hello 0'
从上面的例子中,我可以看到第二个字符串被转换为数字。因此,将具有 valueOf
属性的对象作为函数传递,该函数返回的值将被转换。
> "Hello " + + ({valueOf: function () {return 1; }})
'Hello 1'
正如预期的那样,它显示 "Hello 1"
。
为什么在Number
中转换第二个字符串?为什么不抛出语法错误?
最佳答案
第二个 +
是 unary plus operator其目的是将其操作数转换为数字。
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
"Hello " + + "World!"
只能解析为
"Hello " + (+ "World!")
这是
"Hello " + NaN
因此你的结果。
这个一元运算符在 JavaScript 中非常有用,是将数字或字符串转换为数字的最常用方法之一。与 parseFloat
相比,它还有一个优势,那就是它不是可笑的容忍度(parseFloat("7up")
会返回 7
),这使它成为一种简单的方法查看字符串是否表示数字(只需测试 s==+s
)。
关于javascript - 在 JavaScript 中使用++ 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533941/