在此循环中,++ i和i ++有区别吗? [英] Is there a difference between ++i and i++ in this loop?

查看:108
本文介绍了在此循环中,++ i和i ++有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

array.prototype.reduce函数位于:

The array.prototype.reduce function at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

它具有以下循环:

for (index = 0; length > index; ++index) {
    if (this.hasOwnProperty(index)) {
      if (isValueSet) {
         value = callback(value, this[index], index, this);
      } else {
        value = this[index];
        isValueSet = true;
      }
    }
}

我认为这里的索引是先递增还是后递增都没有区别,因为它是在每次循环迭代之后完成的,但是要确定.

I don't think there is a difference whether the index is pre or post incremented here since it's done after the loop iterates each time, but want to be certain.

可以将其更改为索引+ = 1,以使其通过jslint吗?请不要争论jslint警告的优点.

Can this be changed to index += 1 so it passes jslint? Please don't debate the merits of jslint's warning.

此更改会有所不同吗?

推荐答案

i++++ii += 1之间的唯一区别是从表达式返回的值.请考虑以下内容:

The only difference between i++, ++i, and i += 1 is the value that's returned from the expression. Consider the following:

// Case 1:
var i = 0, r = i++;
console.log(i, r); // 1, 0

// Case 2:
var i = 0, r = ++i;
console.log(i, r); // 1, 1

// Case 3:
var i = 0, r = (i += 1);
console.log(i, r); // 1, 1

在这些情况下,i在增加后保持不变,但r不同,i += 1只是++i的详细形式.

In these cases, i remains the same after the increment, but r is different, i += 1 just being a slightly more verbose form of ++i.

在您的代码中,您根本没有使用返回值,所以不,没有区别.就个人而言,我更喜欢使用i++,除非特别需要使用其他形式之一.

In your code, you're not using the return value at all, so no, there is no difference. Personally, I prefer to use i++ unless there is a specific need to use one of the other forms.

这篇关于在此循环中,++ i和i ++有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆