将数字作为字符串进行加法和减法
我在 SO 的一个问题上读到了以下内容:
在 JavaScript 中,'7' + 4 给出 '74',而 '7' - 4 给出 3
为什么会发生这种情况?
I read the following on a question on SO:
'7' + 4 gives '74', whereas '7' - 4 gives 3 in JavaScript
Why does this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
+
是字符串连接运算符,因此当您执行'7' + 4
时,您会将4
强制转换为字符串并将其附加。-
运算符不存在这样的歧义。如果您想明确使用
parseInt()
或parseFloat()
:为什么将基数指定为 10?因此
'077'
不会被解析为八进制。+
is the String concatenation operator so when you do'7' + 4
you're coercing4
into a string and appending it. There is no such ambiguity with the-
operator.If you want to be unambiguous use
parseInt()
orparseFloat()
:Why specify the radix to 10? So
'077'
isn't parsed as octal.“+”运算符是为字符串和数字定义的,因此当您将其应用于字符串和数字时,数字将被转换为字符串,然后字符串将被连接:
'7' + 4 => '7' + '4' => ‘74’
但 '-' 只为数字定义,而不是字符串,因此字符串 '7' 将被转换为数字:
'7' - 4 => 7 - 4 => 3
The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated:
'7' + 4 => '7' + '4' => '74'
But '-' is only defined for numbers, not strings, so the string '7' will be converted to number:
'7' - 4 => 7 - 4 => 3
JavaScript 中重载了
+
运算符来执行串联和加法。 JavaScript 决定执行哪个操作的方式是基于操作数的。如果其中一个操作数不是Number
类(或number
基元类型),则两者都将被转换为字符串以进行串联。然而,
-
运算符仅适用于数字,因此操作数在运算过程中将始终转换为数字。The
+
operator is overloaded in JavaScript to perform concatenation and addition. The way JavaScript determines which operation to carry out is based on the operands. If one of the operands is not of classNumber
(or thenumber
primitive type), then both will be casted to strings for concatenation.The
-
operator, however, is only for numbers and thus the operands will always be cast to numbers during the operation.因为 + 代表集中,如果你想加两个数字,你应该先解析它们 parseInt() 和 - 符号代表减法
Because + is for concentration, if you want to add two numbers you should parse them first parseInt() and - sign is for subtraction
Javascript 中的符号 + 被解释为先连接然后添加,因为第一部分是字符串('7')。因此,解释器将第二部分 (
4
) 转换为字符串并将其连接起来。至于
'7' - 4
,除了减法之外没有其他意义,因此进行减法。The sign + in Javascript is interpreted as concatenation first then addition, due to the fact that the first part is a string ('7'). Thus the interpreter converts the 2nd part (
4
) into string and concatenate it.As for
'7' - 4
, there is no other meaning other than subtraction, thus subtraction is done.