admin管理员组文章数量:1336631
I have a class with Array as a class member. And I have many class functions that do something with each element of array:
function MyClass {
this.data = new Array();
}
MyClass.prototype.something_to_do = function() {
for(var i = 0; i <= this.data.length; i++) {
// do something with this.data[i]
}
}
MyClass.prototype.another_thing_to_do = function() {
for(var i = 0; i <= this.data.length; i++) {
// do something with this.data[i]
}
}
If there any way to improve this code? I'm searching something like 'map(), filter(), reduce()' in the functional languages:
MyClass.prototype.something_to_do = function() {
this.data.map/filter/reduce = function(element) {
}
}
Any way to remove explicit for-loop.
I have a class with Array as a class member. And I have many class functions that do something with each element of array:
function MyClass {
this.data = new Array();
}
MyClass.prototype.something_to_do = function() {
for(var i = 0; i <= this.data.length; i++) {
// do something with this.data[i]
}
}
MyClass.prototype.another_thing_to_do = function() {
for(var i = 0; i <= this.data.length; i++) {
// do something with this.data[i]
}
}
If there any way to improve this code? I'm searching something like 'map(), filter(), reduce()' in the functional languages:
MyClass.prototype.something_to_do = function() {
this.data.map/filter/reduce = function(element) {
}
}
Any way to remove explicit for-loop.
Share Improve this question asked Aug 14, 2012 at 10:03 cethceth 45.3k63 gold badges189 silver badges300 bronze badges 1- 1 I think it belongs on CodeReview – fardjad Commented Aug 14, 2012 at 10:06
1 Answer
Reset to default 6There is a map()
function in JavaScript. Have a look at the MDN docu:
Creates a new array with the results of calling a provided function on every element in this array.
MyClass.prototype.something_to_do = function() {
this.data = this.data.map( function( item ) {
// do something with item aka this.data[i]
// and return the new version afterwards
return item;
} );
}
Accordingly there are filter()
(MDN) and reduce()
(MDN).
本文标签: javascriptmapfilterreduce with ArrayStack Overflow
版权声明:本文标题:javascript - mapfilterreduce with Array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742233295a2437616.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论