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