简体   繁体   中英

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. 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. 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. Thus "1" + 1 is "11" . But in JavaScript, - only has one meaning, subtraction. 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 + 1

Here, the unary + implicitly converts a to a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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