开发者问题收集

无法在 JS 中使用 uniq 对数组进行 m​​onkey patch [初学者]

2022-05-01
226
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]));

我正在尝试对上述代码进行 monkey patch,但是我收到了:

/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

2个回答

您的代码中有多个错误。触发错误的是箭头函数 ([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() 。此外,您的循环将运行 0 次,因为 i = 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());
Mushroomator
2022-05-01

好的,您犯了几个错误:

  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());
Ilijanovic
2022-05-01