无法在 JS [初学者] 中使用 uniq 修改数组

Unable to monkey patch array using uniq in JS [beginner]

Array.prototype.uniq = function() {
  narr = [];
  for (let i = 0; i < 0; i++) {
    if (!narr.include(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log(([1, 2, 2, 3, 3, 3].uniq() => [1, 2, 3]));

我正在尝试修改上面的代码,但我收到:

/home/cameronnc/Documents/app/skeleton/phase_1_arrays.js:11 console.log(([1,2,2,3,3,3].uniq() => [1,2,3])); ^^^^^

SyntaxError: Malformed arrow function parameter list at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1033:15) at Module._compile (node:internal/modules/cjs/loader:1069:27) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Module._load (node:internal/modules/cjs/loader:827:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) at node:internal/main/run_main_module:17:47

Node.js v18.0.0

您的代码中存在多个错误。触发错误的是箭头函数 ([1, 2, 2, 3, 3, 3].uniq() => [1, 2, 3]),它不是有效的箭头函数。你想要的只是打印 [1, 2, 2, 3, 3, 3].uniq().

的结果

Array.prototype.uniq = function() {
  const narr = [];
  for (let i = 0; i < this.length; i++) {
    if (!narr.includes(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log([1, 2, 2, 3, 3, 3].uniq());

也不是include()而是includes()。此外,自 i = 0 以来,您的循环将 运行 正好 0 次,并且您的条件是 i < 0。将其更改为 i < this.length.

顺便说一下,通过使用 Set,您可以实现相同的行为,但复杂度为 O(n) 而不是像当前实现那样的 O(n²)

Array.prototype.uniq = function() {
  return [...new Set(this)]
}

console.log([1, 2, 2, 3, 3, 3].uniq());

好的,你有几个错误:

  1. 您需要申报narr
  2. 你的 for 循环中的条件没有意义 i < 0。你需要数组的长度 this.length
  3. 打字错误 includeincludes

Array.prototype.uniq = function() {
  let narr = [];
  for (let i = 0; i < this.length; i++) {
    if (!narr.includes(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log([1, 2, 2, 3, 3, 3].uniq());