添加+“”字符串追加“0” [英] Adding +"" to string appends "0"
问题描述
由于偶然的拼写错误,我遇到了一个我无法解释的行为。
By an accidental typo I've encountered a behavior which I cannot explain.
当我有
var text = "abc";
text += + "";
text
变量突然变为 abc0
。
有人可以就此提供任何见解吗?
Can someone provide any insight on this, please?
推荐答案
+
计算结果为 0
。这是因为为了应用一元加运算符,被强制转换为一个数字 - 与
数字()相同
,如果字符串为空或空白,则会产生 0
。
+ ""
evaluates to the number 0
. This is because in order to apply the unary plus operator, ""
is coerced to a number--the same as Number("")
, which results in 0
if the string is empty or blank.
当你然后添加( +
或在这种情况下 + =
)数字 0
到字符串abc
,它被强制转换为字符串0
,结果为abc0
。
When you then "add" (+
or in this case +=
) the number 0
to the string "abc"
, it is coerced to the string "0"
, resulting in "abc0"
.
来自规范:
一个空的StringNumericLiteral或仅包含空格的StringNumericLiteral是转换为+0。
A StringNumericLiteral that is empty or contains only white space is converted to +0.
这篇关于添加+“”字符串追加“0”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!