在稀疏 javascript 数组中查找最大值

Find max value in a sparse javascript array

是否有正确的方法来查找具有未定义值的稀疏数组的最大值?

谢谢

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。

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);

None 你的例子是真正的稀疏数组(他们没有任何 'holes'),但是你可以使用 Array.prototype.filter (ECMA5) to test the value isFinite. For better accuracy ECMA6 will offer Number.isFinite. Remember there are also limits to the number of arguments that Function.prototype.apply can handle (often 65536 arguments). Of course, 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);
}));