2015-01-20 72 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