Javascript(+)符号连接而不是给出变量的总和 [英] Javascript (+) sign concatenates instead of giving sum of variables
本文介绍了Javascript(+)符号连接而不是给出变量的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我使用它:(假设 i = 1
)
Why when I use this: (assuming i = 1
)
divID = "question-" + i+1;
我得到问题-11 而不是问题-2 ?
推荐答案
请改用:
var divID = "question-" + (i+1)
它是一个相当常见的问题,并不只是发生在JavaScript中。我们的想法是 +
可以代表两个连接和添加。
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
:因为问题 -
是一个字符串,我们将进行连接,导致question-1
-
question-1+ 1
:自queston- 1
是一个字符串,我们将进行连接,产生question-11
。
"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"
.
使用question-+(i + 1)
它有所不同:
- 由于
(i + 1)
在括号内,其值必须在第一个之前计算可以应用+
:
-
i
是数字,1
是数字,所以我们会添加,导致2
- 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 in2
这篇关于Javascript(+)符号连接而不是给出变量的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-
查看全文