gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:29:05 26 4
gpt4 key购买 nike

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

谢谢

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

如果有内置方法,我不想这样做。

最佳答案

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

关于javascript - 在稀疏 javascript 数组中查找最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com