2010-01-22 143 views
0

我使用Firefox 3.5.7和Firebug內我試圖測試array.reduceRight函數,它適用於簡單數組但是當我嘗試這樣的事情時,我得到一個NaN。爲什麼?爲什麼reduceRight在Javascript中返回NaN?

>>> var details = [{score : 1}, {score: 2}, {score: 3}]; 
>>> details 
[Object score=1, Object score=2, Object score=3] 
>>> details.reduceRight(function(x, y) {return x.score + y.score;}, 0) 
NaN 

我也嘗試過地圖,至少我可以看到每個元素的.score組件:

>>> details.map(function(x) {console.log (x.score);}) 
1 
2 
3 
[undefined, undefined, undefined] 

我閱讀文檔在https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight但顯然我不能讓它工作總結全部得分值我的詳細資料數組。爲什麼?

回答

6

給函數的第一個參數是累計值。因此,第一次調用該函數將看起來像f(0, {score: 1})。所以當做x.score時,你實際上正在做0.score,當然這不起作用。換句話說,你想要x + y.score

+1

所以基本上,當你通過初始值reduceRight時,它表現爲摺疊。我沒有意識到這一點。 – 2010-01-22 15:17:31

+1

我開悟了!謝謝。 – 2010-01-22 15:34:35

4

試試這個

details.reduceRight(function(previousValue, currentValue, index, array) { 
    return previousValue + currentValue.score; 
}, 0) 

或本

details.reduceRight(function(previousValue, currentValue, index, array) { 
    var ret = { 'score' : previousValue.score + currentValue.score} ; 
    return ret; 
}, { 'score' : 0 }) 

感謝(將轉換爲數字的副作用),以@ sepp2k您指出{ 'score' : 0 }是如何需要作爲參數。

0

reduce函數應該將具有屬性「分數」的兩個對象組合爲具有屬性「分數」的新對象。你將它們組合成一個數字。

+0

該函數應該將a類型的對象和b類型的對象(其中a是初始值的類型,b是數組的元素類型)合併到a類型的對象中。 a和b不必是相同的類型。 – sepp2k 2010-01-22 15:17:39

+0

是的,我意識到這一點。我主要使用Scala,其中reduce操作總是生成一個與輸入列表類型相同的值。在Scala中,將列表中的值累加到另一個類型的值中的操作稱爲fold。 – 2010-01-22 15:35:14