简单的解决方案删除 JS 数组中的重复项。必须使用 push 或 pop 和 forEach

Simple solution remove duplicates in JS array. Must use push or pop and forEach

所以,我还在学习中,所以请原谅简单的性质。但我正在尝试编写一个名为 uniq(arr) 的函数。如果有效,它将 return 一个没有任何重复值的新数组。它不应该更改原始数组。

这是两个目前无法正常工作的测试电话。我不确定错误意味着什么 > uniq([1, 2, 3]) 预期:[1, 2, 3] 但得到:

TypeError: undefined is not an object (evaluating 'copy.includes')

> uniq(['a', 'a', 'b']) 预期:['a','b'] 但得到:TypeError:undefined is not an object (evaluating 'copy.includes')

function uniq(arr) {
  var copy;
  arr.forEach(function(item) {
    if (!copy.includes(item)) {
      push.copy(item);}})
  return copy
}

Set 使数组唯一。

const unique = (arr) => {
  return [... new Set(arr)];
}

console.log(unique([1, 2, 3, 3, 2, 5]))
// Output: [1, 2, 3, 5]

您的代码有 2 个问题。 初始错误来自没有值的副本。你需要给它一个空数组的值才能调用它的数组方法,例如

 var copy = [];

第二个错误是您使用 push 方法的方式。您需要调用数组推送而不是相反(见下文)

copy.push(item);

解决这些问题让我们得到这个工作示例

function uniq(arr) {
  var copy = [];
  arr.forEach(function(item) {
    if (!copy.includes(item)) {
      copy.push(item);
    }
  });
  
  return copy;
}

console.log(uniq(['a', 'a', 'b']));