Javascript (+) sign concatenates instead of giving

2019-01-01 03:41发布

Why when I use this: (assuming i = 1)

divID = "question-" + i+1;

I get question-11 and not question-2?

13条回答
心情的温度
2楼-- · 2019-01-01 04:21
divID = "question-" + parseInt(i+1,10);

check it here, it's a JSFiddle

查看更多
刘海飞了
3楼-- · 2019-01-01 04:22

Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:

i = i + 1;
divID = "question-" + i;

Or you need to specify the number addition like this:

divID = "question-" + Number(i+1);

EDIT

I should have added this long ago, but based on the comments, this works as well:

divID = "question-" + (i+1);
查看更多
与君花间醉酒
4楼-- · 2019-01-01 04:22
var divID = "question-" + (parseInt(i)+1);

Use this + operator behave as concat that's why it showing 11.

查看更多
还给你的自由
5楼-- · 2019-01-01 04:27

Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.

Use parseInt(i) than the value of "i" will be casted to Integer.

Than the "+" operator will work like addition.

In your case do this :-

divID = "question-" + parseInt(i)+1;
查看更多
闭嘴吧你
6楼-- · 2019-01-01 04:30

Use this instead:

var divID = "question-" + (i+1)

It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.

Since the + operator will be handled left-to-right the decisions in your code look like this:

  • "question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
  • "question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".

With "question-" + (i+1) it's different:

  • since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
    • i is numeric, 1 is numeric, so we'll do addition, resulting in 2
  • "question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
查看更多
伤终究还是伤i
7楼-- · 2019-01-01 04:31

You may also use this

divID = "question-" + (i*1+1); 

to be sure that i is converted to integer.

查看更多
登录 后发表回答