let arr = [3, 56, 0, 21, -7, 39];
1.遍历数组每一项与当前最大值比较
Array.prototype.max = function () { //将数组的第一个元素赋值给max let max = this[0]; this.forEach((item, index) => { //将当前值item与max比较 max = max > item ? max : item }) return max; }2.sort()排序,a-b升序,b-a降序
let max = arr.sort((a,b)=>{ return a-b; })[0];注意:若arr.sort()不带参数,则按照字符编码的顺序进行排序
let max= arr.sort(); console.log(arr.max(), arr1, arr2, arr3, arr4);3.内置函数Math.max,可以传递多个参数。
max()里面参数不能为数组,借助apply(funtion,args)方法调用Math.max(),当function为null时,默认为上文,即相当于apply(Math.max,arr)
let max=Math.max.apply(null,arr);console.log(max);call()与apply()类似,区别是传入参数的方式不同,apply()参数是一个对象和一个数组类型的对象,call()参数是一个对象和参数列表
var max1 = Math.max.call(null,3, 0, -7, 39);console.log(max1);4.扩展运算符…
let max=Math.max(...arr);