JavaScript中的++ i和i ++有什么区别 [英] What's the difference between ++i and i++ in JavaScript
问题描述
在寻求学习和改进JavaScript的过程中,我遇到了一个带有switch/case语句的脚本,我注意到使用++在++之前加上一些变量,然后在++之后加上一些变量.变量.这些有什么区别?这是我要解释的示例,请注意m和y变量.
on my quest to learn and improve my JavaScript I came across a script that has a switch / case statement and I noticed some variables are incremented using ++ with the variable before the ++ and then some variables have the ++ after the variable. What's the difference between these? Here's an example of what I'm trying to explain notice the m and y variables.
switch(f){
case 0:{
++m;
if(m==12){
m=0;
y++;
}
break;
}
case 1:{
--m;
if(m==-1){
m=11;
y--;
}
break;
}
case 2:{
++y;
break;
}
case 3:{
--y;
break;
}
case 4:{
break;
}
}
推荐答案
++i
在增加i
的值后返回. i++
在递增之前返回i
的值.
++i
returns the value of i
after it has been incremented. i++
returns the value of i
before incrementing.
当++
出现在其操作数之前时,它称为前递增"运算符,当它出现在其之后时,则称为后递增"运算符.
When the ++
comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator.
仅当您对结果进行某些操作时,这种区别才重要.
This distinction is only important if you do something with the result.
var i = 0, j = 0;
alert(++i); // alerts 1
alert(j++); // alerts 0
要注意的一件事是,即使i++
在递增之前返回该值,但在将其转换为数字后仍会返回该值.
One thing to note though is that even though i++
returns the value before incrementing, it still returns the value after it has been converted to a number.
所以
var s = "1";
alert(typeof s++); // alerts "number"
alert(s); // alerts 2, not "11" as if by ("1" + 1)
这篇关于JavaScript中的++ i和i ++有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!