javascript - 扩展 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)
解决方案
当您在循环期间将值推送到同一个数组时,您将进入无限循环,创建一个临时数组推送值,最后将其添加到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 - JavaScript 将参数传递给保持参数数据完整的函数
- javascript - 上传和显示图像 - ReactJs、Node.js
- list - 动态表数据渲染 react native
- function - 当您编写 Powershell 函数时,它在内存中持续多长时间?
- html - 如何更改我在后台找不到的一些文本
- c++ - ArrayFire GFOR 循环意外错误
- apache-spark - 如何在写入数据时使用“Salt”进行火花重新分区
- python - 如何将xml xpath解析为list python
- javafx - 如何将 javaFx 中的按钮链接到 rpi 上的 gpio 引脚
- c# - 如何使用 oData 查询从 azure graph API 过滤结果