首页 > 解决方案 > 扩展 Array.prototype 崩溃

问题描述

我试图解决我在博客上遇到的以下问题,但程序崩溃了。可能是什么原因?有什么办法解决吗?我已阅读不要扩展内置对象的警告,如果是这种情况,与此特定示例相关的原因可能是什么。

const a = [1, 2, 3, 4, 5];

//this is what I tried
Array.prototype.multiply = function() {
  for (m of this) this.push(m * m);
}

a.multiply(); //this should not be changed
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25] (expected output)

标签: javascriptarraysforeachprototype

解决方案


当您在循环期间将值推送到同一个数组时,您将进入无限循环,创建一个临时数组推送值,最后将其添加到this

const a = [1, 2, 3, 4, 5];

//this is the what I tried
Array.prototype.multiply = function() {
  let newArr = []
  for (const m of this) {
    newArr.push(m * m)
  }
  this.push(...newArr)
}

a.multiply();
console.log(a);

话虽这么说,您不应该重写prototype简单地使用函数并传递参数

const a = [1, 2, 3, 4, 5];

function multiply(arr) {
  return [...arr, ...arr.map(a => a * a)]
}

console.log(multiply(a));


推荐阅读