知方号

知方号

js求数组最大值的四种方法

js求数组最大值的四种方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。