简体   繁体   English

JavaScript中a +1和a-1 +2有什么区别

[英]What is the difference between a + 1 and a - 1 +2 in javascript

I got a project and found very mysterious one. 我得到一个项目,发现一个非常神秘的项目。
I found a - 1 + 2 in javascript code and I thought it will same as a + 1 and replaced with it. 我在JavaScript代码中找到a - 1 + 2 ,我认为它将与a + 1相同,并替换为它。 But it is making wrong answer. 但这是错误的答案。 when 什么时候

a = 1 => a -1 +2 = 2
      => a + 1 = 11

Can anyone describe about this issue? 谁能描述这个问题?

a is a string. a是一个字符串。 Because + can mean addition or string concatenation , that's what you're seeing here. 因为+可以表示加法或字符串连接 ,所以这就是您在这里看到的。 In JavaScript, if you have at least one addend that is a string, both operands are coerced to strings and concatenated. 在JavaScript中,如果您至少有一个字符串加数,则两个操作数都将被强制转换为字符串并进行连接。 Thus "1" + 1 is "11" . 因此, "1" + 1"11" But in JavaScript, - only has one meaning, subtraction. 但是在JavaScript中,-只有一种含义,即减法。 Thus it converts both operands to numbers and subtracts. 因此,它将两个操作数都转换为数字并相减。 No concatenation occurs with subtraction, hence the difference. 减法不会发生串联,因此是不同的。

Just coerce a into an integer before adding: 只需在添加之前将a强制为整数:

+a + 1

Here, the unary + implicitly converts a to a number. 在此,一元+隐式将a转换为数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM