如何在 JavaScript 数组中查找不包括 undefined 元素的最大值?
我们需要编写一个 JavaScript 函数,该函数接受一个数组,其中包含一些数字、字符串和一些错误值。
我们的函数应该返回数组中最大的数字。
例如 -
如果输入数组如下,其中包含一些 undefined 值 -
const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
则输出应为 65
示例
以下是代码 -
const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];
const pickBiggest = arr => {
let max = -Infinity;
for(let i = 0; i < arr.length; i++){
if(!+arr[i]){
continue;
};
max = Math.max(max, +arr[i]);
};
return max;
};
console.log(pickBiggest(arr));输出
这将在控制台上产生以下输出 -
65
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP