【发布时间】:2018-04-20 09:46:32
【问题描述】:
在 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)
【问题讨论】:
-
边做边学和使用 Stackoverflow 是学习 JavaScript 的好方法。您可能还喜欢这篇文章中描述的删除重复项的替代方法:stackoverflow.com/questions/9229645/…
标签: javascript arrays node.js foreach