admin管理员组文章数量:1429064
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]?
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]?
-
1
The
.forEach()
function does not return a value. – Pointy Commented Feb 12, 2014 at 16:22 -
NB: if available, use
Object.defineProperty(Array.prototype, 'square', { value: function() { ... } })
to prevent your function being an enumerable property of every array instance. – Alnitak Commented Feb 12, 2014 at 16:25
2 Answers
Reset to default 7The 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 ment 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.
本文标签: javascriptExtending Arrayprototype returning undefinedStack Overflow
版权声明:本文标题:javascript - Extending Array.prototype returning undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745542836a2662572.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论