最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mapfilterreduce with Array - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 6

There 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).

发布评论

评论列表(0)

  1. 暂无评论