为什么++在字符串上给出奇怪的结果

Why + + on strings gives strange result

我正在使用 jQuery 动态附加元素,发现当使用 + + 时它显示 NaN 并且没有添加下一个文本。

我猜想 + + 在这里用作算术加运算符和 returns NaN.

这不是增量运算符,因为在两个 +.

之间有 space

我的问题是

  1. 这里实际发生了什么所以它 returns NaN
  2. 为什么这里的 + 被字符​​串包围时不能用作连接运算符。

$('#message').html('<span>' + + ' new message</span>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>

可以在 Node.js

中看到相同的行为
> 'a' + + 'b' // aNaN

注意:我知道我在这里添加了一个额外的 + 并且删除它对我有用。

因为第二个 + 被评估为 unary plus 运算符,如

'<span>' + + ' new message</span>'
= '<span>' + (+' new message</span>')
= '<span>' + NaN
= <span>NaN

原因是因为通过将 + 字符放在字符串之前,您试图将 'b' 字符串转换为数字,从而导致 NaN。您问题中的代码等同于:

'a' + Number('b')

因此 Number('b') returns NaN 然后被强制转换为字符串并附加到 a。这种行为是 JS 固有的,因此所使用的库(无论是 jQuery、节点还是任何其他库)都是无关紧要的。

+ 运算符可用于将变量转换为数字。所以这个...

"a" + + "b"

returnsaNaN,但这...

"a" + + "5"

returns a5

因为 b 不是数字,所以 + b returns NaN。

你可以这样试试:

$('#message').html('<span>' + ' new message</span>');

 $('#message').html('<span>' + '' + ' new message</span>');

==========================================

$('#message').html('<span>' + ' new message</span>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>

javascript首先尝试将字符串'b'转换为数字,returnsNaN因为'b'无法转换为数字。然后 'a' + 'NaN' 连接到新字符串 'aNaN'。与您的示例相同:

$('#message').html('<span>' + + ' new message</span>');

Javascript 尝试将 + ' new message</span>' 转换为数字和 returns NaN。然后 '<span>' + 'NaN' 创建一个新的 span 元素和 NaN 作为文本。

看看:

Unary plus (+)

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.