是否有正确的方法来查找具有未定义值的稀疏数组的最大值?
由于
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 :(得分:2)
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);
答案 1 :(得分:2)
您的所有示例都不是真正的稀疏数组(它们没有任何'漏洞'),但您可以使用Array.prototype.filter
(ECMA5)来测试值{{3} }。为了更好的准确性,ECMA6将提供isFinite
。请记住,Number.isFinite
可以处理的参数数量也有限制(通常为65536个参数)。当然,Function.prototype.apply
可能不适合您的应用,如果您需要Infinity
和-Infinity
,那么您应该使用不同的测试。在当前的例子中,带有负数的空字符串将是一个问题。
var testArr = [undefined, , , 3, 4, 5, 6, 7];
document.body.textContent = Math.max.apply(null, testArr.filter(function (x) {
return isFinite(x);
}));