JavaScript 增量
我知道你可以简单地通过执行 i++
(假设 i 是你的变量)来向变量添加 1。当迭代数组或在“for”语句中使用它时,可以最好地看到这一点。在网上找到一些可以使用的代码后,我注意到 for 语句使用了 ++i
(与 i++
相对)。
我想知道是否有任何显着差异,或者两者的处理方式是否有不同。
Possible Duplicate:
++someVariable Vs. someVariable++ in Javascript
I know you can add one to a variable simply by doing i++
(assuming i is your variable). This can best be seen when iterating through an array or using it in a "for" statement. After finding some code to use online, I noticed that the for statement used ++i
(as apposed to i++
).
I was wondering if there was any significant difference or if the two are even handled any differently.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,有很大差异。
这是一个将它们放在一起的小提琴: http://jsfiddle.net/maniator/ZcKSF/
Yes there is a big difference.
And here is a fiddle to put it all together: http://jsfiddle.net/maniator/ZcKSF/
++i
的值为i + 1
,i++
的值为i
。两者之一求值后,i
为i + 1
。这是时间上的差异,这就是为什么它们通常被称为“前增量”和“后增量”。但在 for 循环中,这并不重要。The value of
++i
isi + 1
and the value ofi++
is justi
. After either has evaluated,i
isi + 1
. It's a difference in timing, which is why they're often called 'pre-increment' and 'post-increment'. In a for loop, it rarely matters, though.像 Douglas Crockford 这样的人建议不要使用这种递增方式,其中之一就是 Rafe Kettler 所描述的原因。无论您多么有经验,有时
++i/i++
都会让您感到惊讶。另一种方法是使用i += 1
简单地将i加1,可读、可理解且明确。People like Douglas Crockford advise not to use that way of incrementing, amongst other reasons because of what Rafe Kettler described. No matter how experienced you are, sometimes
++i/i++
will suprise you. The alternative is to simply add 1 to i usingi += 1
, readable, understandable and unambiguous.看看这个链接:http://www.w3schools.com/js/js_operators.asp< /a>
这是后增量与预增量的比较。它们最终都会递增值,但一个返回递增之前的值 (++y),另一个返回递增之后的值 (y++)。
但是,在 for 循环中使用它时没有任何区别 -
与
have a look at this link : http://www.w3schools.com/js/js_operators.asp
it's post increment versus pre increment. They both end up incrementing the value but one returns the value BEFORE incrementing (++y) and the other one returns the value AFTER (y++).
However, it doesn't make any difference when using it in a for loop --
is the same as
现在如果你打印 a,b,c,d..输出将是:
2 2 2 1
now if you print a,b,c,d..the output will be:
2 2 2 1
++i 称为前自增,i++ 称为后自增。不同之处在于变量何时递增。预自增通常是变量加1然后使用该值,而后自增通常是先使用变量然后自增。
++i is called pre-increment and i++ is called post-increment. The difference is when the variable is incremented. Pre-incrementing a variable usually adds 1 and then uses that value, while post-incrementation uses the variable and then increments.