求数组中最大的值

JavaScript 中有 Math.max返回最大值,但是

console.log(Math.max(5,8))    //8
console.log(Math.max(5,7,9,3,1,6))    //9

如上,它在所有入参中返回最大的值

 很多情况下,我们需要找出数组中最大的元素,

var arr = [1,2,3,4,5,6,7] ;
console.log(Math.max(arr));   // NaN 

我们可以这样

var max=Math.max.apply(null,arr)
console.log('最大值:'+max)

在上边的代码中,我们通过 apply 将一个数组元素分离,一个接一个的作为参数传递给方法;Math.max.apply(null,array) 第一项为null ,是因为不需要对象去引用它,得到返回结果就行。

未完,待续......
原文地址:https://www.cnblogs.com/zhishiyv/p/14480336.html