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"
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…