Javascript (+) sign concatenates instead of giving sum of variables

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

divID = "question-" + i+1;

I get question-11 and not question-2?

154120 次浏览
divID = "question-" + parseInt(i+1,10);

check it here, it's a JSFiddle

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);

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".

Add brackets

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

using braces surrounding the numbers will treat as addition instead of concat.

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

You may also use this

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

to be sure that i is converted to integer.

The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.

In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".

You just simply need to give the interpreter a hint as to what order of prec endence you want.

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

Use only:

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

When "n" comes from html input field or is declared as string, you need to use explicit conversion.

var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);

If "n" is integer, don't need conversion.

n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;

Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.

For example: You are passing “sum of value of an input element and an integer” as an argument to a function.

arg1 = $("#elemId").val();   // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2);    // and so the values are merged here
someFuntion((arg1 + arg2));  // and here

You can make it work by using Number()

arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);

or

arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);

One place the parentheses suggestion fails is if say both numbers are HTML input variables. Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.

  • HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
  • Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
  • From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.

Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.

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;
var divID = "question-" + (parseInt(i)+1);

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

Another alternative could be using:

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

Subtracting a negative is the same as adding, and a minus cannot be used for concatenation

Edit: Forgot that brackets are still necessary since code is read from left to right.

Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.

It is a good practice to initialize variables of declaration:

  • In case of integers, var num = 0;
  • In case of strings, var str = "";

Even if your i variable is integer, + operator can perform concatenation instead of addition.

In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.

- (minus operator) cannot be misunderstood and you will not get unexpected result/s.