js取数组中的最大值

js取数组中的最大值

js取数组中的最大值,有四种方法

原文地址:https://www.cnblogs.com/lguow/p/9725258.html

一、借助apply(),获得最大值

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

由于max()里面参数不能为数组,所以借助apply(funtion,args)方法调用Math.max(),function为要调用的方法,args是数组对象,当function为null时,默认为上文,即相当于apply(Math.max,arr)

二、借助call(),获得最大值

var arr = [1, 2, 3, 4, 5, 6]
var max1 = Math.max.call(null,7,2,0,-3,5)
console.log(max1)

call()与apply()类似,区别是传入参数的方式不同,apply()参数是一个对象和一个数组类型的对象,call()参数是一个对象和参数列表

三、sort()+reverse()

var arr = [1, 2, 3, 4, 5, 6]
var max3 = arr.sort().reverse()[0];
console.log(max3)

sort()排序默认为升序,reverse()将数组掉个

三、sort()

var arr = [1, 2, 3, 4, 5, 6]
var max2 = arr.sort(function(a,b){
    return b-a;
})[0];
console.log(max2)

b-a从大到小,a-b从小到大
在这里插入图片描述

欢迎关注我的个人技术公众号

  • 14
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值