在Ubuntu中使用nodejs。我一直在阅读 JavaScript forEach()
方法的 MDN 文档。我知道还有其他方法可以做到这一点,但我通过实践来学习;我试图使数组 copy
成为 arr
数组中值的唯一集合;没有重复项。我想使用 forEach()
方法来执行此操作。
设置:
var arr = [1, 2, 3, 4, 4, 3, 2];
var copy = [];
那么为什么这会起作用呢?
copy.includes(1); // returns false
虽然这不是?
arr.forEach(function(element, copy) {
if (!copy.includes(element)) {
copy.push(element);
}
});
这是错误:
TypeError: copy.includes is not a function
at repl:2:11
at Array.forEach (native)
at repl:1:5
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at REPLServer.defaultEval (repl.js:339:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:536:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:191:7)
最佳答案
尝试:
arr.forEach(function(element) {
if (!copied.includes(element)) {
copied.push(element);
}
});
forEach 回调的第二个参数是索引,而不是您要填充的数组。此外,您引用的 copy
是 undefined
,而根据您的代码示例,正确的变量名称是 copied
。
编辑
编辑完代码后,您可以使用名称 copy
来表示 forEach 回调的数组和第二个参数(为什么您需要 forEach 回调的第二个参数 - 顺便说一句 - 是索引,而不是“复制” - 无论您指的是什么副本:P)。
因此,您会收到一个错误,指出 Number.prototype
没有名为 includes()
的方法,这是正确的,因为索引是一个 Number
。
总结一下:
arr.forEach(function(element) {
if (!copy.includes(element)) {
copy.push(element);
}
});
关于JavaScript forEach() 方法混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47167291/