javascript - 扩展 Array.prototype 崩溃

标签 javascript arrays foreach 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)

最佳答案

当您在循环期间将值插入同一数组时,您最终会陷入无限循环,创建一个临时数组将值推送到它,最后将其添加到 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));

关于javascript - 扩展 Array.prototype 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58244973/

相关文章:

php - 如何在循环时以及在数组内部插入数据

Java - Integer[] 和 int[] 内存差异

php - foreach 数组是更改网页上 sql 列名称的最佳选择吗?

php - 在 WooCommerce 中按产品获取类别 ID

javascript - 添加 JavaScript 最小长度验证到文本字段?

javascript - d3 circle packing 如何在两次单击同一节点时不缩小

javascript - 如何将焦点设置到页面上的 slickgrid 控件以启用键盘导航?

javascript - 将json对象插入javascript中的有序数组

php - 抓取并生成 RSS 提要

javascript - 带有 templateResult 和 templateSelection 的 jquery select2 (4.0) ajax