javascript - 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
突然变得不确定。想法?
解决方案
您需要使用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()
正确调用。
推荐阅读
- javascript - 在使用 vue cli 3 创建的项目中,在哪里可以找到或如何设置 htmlWebpackPlugin.options.title?
- rust - 如何按扩展名过滤文件名列表?
- c# - Socket.BeginReceiveFrom 和 Socket.BeginReceiveMessageFrom 有什么区别?
- azure - SQL Data Sync Agent 2.0 安装错误系统服务
- scala - Scala IDE 中的 Spark SaveAsTextFile() 创建“temporay->0”文件夹结构,而不是函数中提到的那个
- python - 为什么函数顺序的顺序很重要?
- gitlab - 如何从 GitLab 13 ci 构建过程中排除主分支?
- gmail - 如何将这个被阻止的附件从 gmail 导入到另一个 gmail?
- html - 当我在 xslt 中迭代时,如何同时从两个不同的节点/元素中获取文本?
- c# - 访问传递的参数 MVC Xhttp.Send()