2015-01-20 64 views
0

有沒有找到含有未定義值的稀疏數組的最大值的正確方法?在一個稀疏的javascript數組中尋找最大值

感謝

var testArr=[undefined,undefined,undefined,3,4,5,6,7]; 
console.log('max value with undefined is ',(Math.max.apply(null,testArr))); 

// max value with undefined is NaN 

console.log('max with arr.max()',testArr.max());  

// Error: testArr.max is not a function  

testArr=[null,null,null,3,4,5,6,7]; 
console.log('max value with null is ',(Math.max.apply(null,testArr))); 

// max value with null is 7 

我不想做的forEach如果有一個內置的方法。

+0

的forEach是一個內置的方法的 – 2015-01-20 21:55:09

+0

可能重複的[JavaScript的:最大和最小數組值](http://stackoverflow.com/questions/1669190/javascript-min- max-array-values) – JAL 2015-01-20 21:55:12

+0

@DanielWeiner內置方法*查找最大值* – glyph 2015-01-20 22:00:33

回答

1
testArr.reduce(function(a,b){ 
    if (isNaN(a) || a === null || a === '') a = -Infinity; 
    if (isNaN(b) || b === null || b === '') b = -Infinity; 
    return Math.max(a,b) 
}, -Infinity); 
+0

負數的空字符串會成爲一個問題。 – Xotic750 2015-01-20 22:48:44

+0

好,我只是更新了我的解決方案,以解釋空字符串。 – 2015-01-20 22:49:24

2

的你的例子都不是真正的稀疏數組(他們沒有任何「洞」),但你可以使用Array.prototype.filter(ECMA5)來測試值isFinite。爲了獲得更好的精度,ECMA6將提供Number.isFinite。請記住,Function.prototype.apply可以處理的參數數量(通常爲65536個參數)也有限制。當然,isFinite可能不適合您的應用程序,如果您想要Infinity-Infinity,那麼您應該使用不同的測試。負數的空字符串將成爲本次測試中的一個問題。

var testArr = [undefined, , , 3, 4, 5, 6, 7]; 
 

 
document.body.textContent = Math.max.apply(null, testArr.filter(function (x) { 
 
    return isFinite(x); 
 
}));

+2

簡單地'testArr.filter(isFinite)' – georg 2015-01-20 23:12:03

+0

@georg是的,我在想,讓它冗長可能會更好的答案,因爲不清楚「isFinite」是提出問題的最佳檢查。 – Xotic750 2015-01-20 23:18:05