首页 > 解决方案 > forEach 没有定义——为什么?

问题描述

Eloquent JavaScript,第 1 版,第 77 页中,它给出了一个从头开始构建映射函数的示例:

function mapFunc(func, array) {
var result = []; // not touching the original!
console.log("array:", array)
forEach(array, function(element) {
    result.push(func(element));
    });
    return result;
}

看起来很简单,但是当它像这样运行时:

console.log(mapFunc(Math.round, [0.01, 2, 9.89, Math.PI]))

它抛出一个错误:

ReferenceError: forEach is not defined

即使我更改内容以更匹配 es6 语法,同样的问题:

array.forEach(function(element) {
    result.push(func(element))
    console.log(element)
})

我已经搞砸了一段时间,无法弄清楚问题可能是什么,或者为什么forEach突然变得不确定。想法?

标签: javascriptforeach

解决方案


您需要使用array.forEach,并且需要正确调用mapFunc()。您将数组作为第二个参数传递给console.log()而不是mapFunc().

function mapFunc(func, array) {
  var result = []; // not touching the original!
  console.log("array:", array)
  array.forEach(function(element) {
    result.push(func(element));
  });
  return result;
}

console.log(mapFunc(Math.round, [0.01, 2, 9.89, Math.PI]));

本书forEach()在本章前面定义了一个自己的函数。

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

如果您将该函数添加到您的代码中,您应该能够mapFunc()像您第一次编写它一样使用该函数。但无论哪种情况,您都需要mapFunc()正确调用。


推荐阅读