150
rated 0 times
[
151]
[
1]
/ answers: 1 / hits: 155786
/ 13 Years ago, wed, may 11, 2011, 12:00:00
Why when I use this: (assuming i = 1
)
divID = question- + i+1;
I get question-11 and not question-2?
More From » math
Why when I use this: (assuming i = 1
)
divID = question- + i+1;
I get question-11 and not question-2?
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:
(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
.