JavaScript数组操作:寻找最大元素与处理空元素

JavaScript未提供直接获取数组最大元素的函数,但可结合 apply 方法和 Math.max 方法实现:

var a = [10, 2, 4, 15, 9]; 
Math.max.apply(null, a) // 返回 15

数组中的空元素可借助 apply 方法和 Array 构造函数转换为 undefined

Array.apply(null, ['a', ,'b']) // 返回 ['a', undefined, 'b']

空元素与 undefined 的区别在于遍历行为,forEach 方法会跳过空元素,但不会跳过 undefined

pdf 文件大小:6.11MB