添加String with Integer如何在JavaScript中工作?
以下代码给出了奇怪的结果:
The following code gives weird results:
console.log("" + 1 + 10 + 2 - 5 + "8");
我已经尝试输入各种不同的值来解决它但我无法理解幕后发生的事情。
I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.
"" + 1 === "1"
"1" + 10 === "110"
"110" + 2 === "1102"
"1102" - 5 === 1097
1097 + "8" === "10978"
在JavaScript中, +
运算符用于数字加法和字符串连接。当您向字符串添加数字时,解释器会将您的数字转换为字符串并将它们连接在一起。
In JavaScript, the +
operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.
当您使用 -
运算符,然而,字符串被转换回数字,以便可能发生数字减法。
When you use the -
operator, however, the string is converted back into a number so that numeric subtraction may occur.
当你然后添加一个字符串8
,再次发生字符串连接。数字 1097
被转换为字符串1097
,然后加入8
。
When you then "add" a string "8"
, string concatenation occurs again. The number 1097
is converted into the string "1097"
, and then joined with "8"
.