2011-07-25 28 views
11

可能重複:
How to use Math.max, etc. as higher-order functions爲什麼我不能在Javascript中編寫[1,2,3] .reduce(Math.max)?

使用Mozilla的JavaScript 1.6數組 '擴展' 功能(地圖,減少,過濾器等),那爲什麼下面將按預期:

var max = [1,2,3].reduce(function(a,b) { return Math.max(a,b); }); 

但以下不起作用(它產生NaN):

var max2 = [1,2,3].reduce(Math.max); 

是否因爲Math.max是一個可變參數函數?

+3

不完全的話題,但如果你想輕鬆地減少陣列到最大值,您可以用'。適用()''上Math.max'。 'var max = Math.max.apply(null,[1,2,3,4]);' – user113716

回答

12

Math.max不知道如何處理所有額外的變量function(previousValue, currentValue, index, array)主要是數組在最後。

[].reduce.call([1,2,3,6],function(a,b) { return Math.max(a,b); }); 

這工作,並使用.call

+1

等等,我明白了...我忘記了傳遞給傳遞給reduce的函數的'extra'參數。所以max也試圖在這些額外的參數上找到最大值。 – sacheie

+0

right和'Math.max(1,[1,2,3])'''NaN' – Joe

+4

如果你要傳遞一個數組作爲'this'值,爲什麼要使用.call()?這只是一個過分複雜的方式,來做OP已經在問題中顯示的內容。 – nnnnnn

相關問題