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;
我得到的是 question-11 而不是 question-2?
I get question-11 and not question-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-"
是一个字符串,我们将进行连接,结果是"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屋!
查看全文