2012-08-14 66 views
2

我有一個Array類作爲類成員的類。我有許多類功能可以對數組中的每個元素執行一些操作:map/filter/reduce與數組

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] 
    } 
} 

如果有任何改進此代碼的方法嗎?我在尋找「)地圖(),濾波器(),降低(」在功能語言是這樣的:

MyClass.prototype.something_to_do = function() { 
    this.data.map/filter/reduce = function(element) {  
    } 
} 

任何方式除去明確的for循環。

+1

我認爲它屬於[** CodeReview **](http://codereview.stackexchange.com/) – fardjad 2012-08-14 10:06:04

回答

6

JavaScript中有一個map()函數。看看MDN docu

創建一個新數組,其結果是調用此數組中每個元素上提供的函數的結果。

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; 
    }); 
} 

因此有filter()MDN)和reduce()MDN)。