for循环的替代方法

ken*_*ken 0 javascript arrays oop node.js

如何使用.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)
Run Code Online (Sandbox Code Playgroud)

这将记录6。

我试过了

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

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

Poi*_*nty 6

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

Array.from(arguments).forEach((arg) => {
  this.score += arg;
});
Run Code Online (Sandbox Code Playgroud)

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

重要的是要注意,如果arguments对象是从函数中传递出来的(如此处所示),则整个函数可能被认为不符合优化条件。这是因为arguments对象具有一些怪异的属性,这使得优化器很难知道正在发生的事情以及对局部变量如何变化进行假设是否安全。如果这是一个问题,那么唯一的选择是将参数复制到带有for循环的简单数组中。