我试图解决以下问题,但该问题在我的博客上崩溃了。可能是什么原因?有什么解决办法吗?我已经阅读过警告,请不要扩展内置对象,如果是这样的话,这可能是与此特定示例相关联的原因。
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));
将新值推入for ... of
循环中间的数组会创建一个无限循环,因为该循环包含新值。您可以改用forEach
,因为它会忽略添加的新值: