I'm trying to extend Array.prototype to include a square function. I have this:
Array.prototype.square = function(){
return this.forEach(function(el){
return (el * el)
});
}
When I call this function on an array, say arr = [2, 2, 2] it returns undefined. If I add a console.log in there I can see that the callback function for the forEach function executes properly -- it logs 4 three times. Why is this function returning undefined instead of a new array of [4, 4, 4]?
The forEach method does not return a value. You need to use map:
Array.prototype.square = function(){
return this.map(function(el){
return (el * el)
});
}
console.log([2, 2, 2].square()); // [4, 4, 4]
As p.s.w.g. said, .map is the appropriate function, but in a comment you asked about using forEach. To get this to work, you'd have to create a temporary array:
Array.prototype.square = function(){
var tmp = [];
this.forEach(function(el){
tmp.push(el * el)
});
return tmp;
}
console.log([2, 2, 2].square()); // [4, 4, 4]
.map() is better, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With