【问题标题】:alternative to for loop [duplicate]for循环的替代品[重复]
【发布时间】:2016-04-22 07:23:46
【问题描述】:

如何使用 .forEach 代替 for 循环?

'use strict';

var score = (function(){
        function updateScore() {
            for(var i = 0; i < arguments.length; i++) {
                this.score += arguments[i];
            }// I want to use .forEach here instead of for loop.
            return this.score;
        }

        return {
            update: updateScore
        }
})();

var soccer = {
    name: 'Soccer',
    score: 0
}

score.update.apply(soccer, [1,2,3])

console.log(soccer.score)

这将记录 6。

我试过了

function updateScore() {
  arguments.forEach((args, i) => {
    this.score += args[i];
  };
  return this.score;
}; 

错误日志:arguments.forEach 不是函数

【问题讨论】:

标签: javascript arrays node.js oop


【解决方案1】:

在现代 (ES2015) JavaScript 中,您可以使用 Array.from()

Array.from(arguments).forEach((arg) => {
  this.score += arg;
});

您不需要使用数组索引,因为.forEach() 函数将每个数组元素作为第一个参数传递给回调函数。 (它确实将索引作为第二个参数传递,但在这种情况下您不需要使用它。)

请务必注意,如果将 arguments 对象从函数中传递出来(就像这里一样),则可能会认为整个函数不符合优化条件。那是因为arguments 对象有一些奇怪的属性,这使得优化器很难知道发生了什么,以及对局部变量如何变化做出假设是否安全。如果这是一个问题,那么唯一的选择是将参数复制到一个带有for 循环的简单数组中。

【讨论】:

  • 这很有帮助!有效。再过 7 分钟,我可以检查它。谢谢!
猜你喜欢
  • 2015-02-08
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多