Reputation: 2530
I was trying to solve the following problem which I got on a blog but the program crashes. What could be the reason? and is there any means of solving it? I have read warnings not to extend builtin objects, if that's the case, what could be the reason associated with this specific example.
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)
Upvotes: 2
Views: 82
Reputation: 37755
When you push the value to same array during loop, you end up in infinite loop, create a temp array push value to it, in the end add it to 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);
That being said you should not override the prototype
simply use a function and pass the parameters
const a = [1, 2, 3, 4, 5];
function multiply(arr) {
return [...arr, ...arr.map(a => a * a)]
}
console.log(multiply(a));
Upvotes: 3
Reputation: 147206
Pushing a new value into an array in the middle of a for ... of
loop creates an infinite loop as the loop includes the new values. You can use forEach
instead as that ignores the new values added:
const a = [1, 2, 3, 4, 5];
Array.prototype.multiply = function() {
this.forEach(v => this.push(v*v));
}
a.multiply(); //this should not be changed
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25] (expected output)
Upvotes: 1