为什么 Math.max.apply(null,arr) 可以求最大最小值

function findLongestWord(str) {
    // 第1步:将传给str的值为:"May the force be with you"转成数组
    var arr = str.split(" "); 

    // 得到数组 arr = ["May", "the", "force", "be", "with", "you"]
    var arrNum = [];

    //  第2步: 对数组arr做遍历
    for (var i = 0; i < arr.length; i++) { // arr.length = 6
        // 将数组arr中每个元素的长度length放到一个新数组arrNum中
        arrNum.push(arr[i].length);
        /*
         * 遍历次数  i = ?  i < arr.length  i++  arr[i]  arr[i].length  arrNum
         * 1st      0      yes              1    "May"     3           [3]
         * 2nd      1      yes              2    "the"     3           [3,3]
         * 3rd      2      yes              3    "force"   5           [3,3,5]
         * 4th      3      yes              4    "be"      2           [3,3,5,2]
         * 5th      4      yes              5    "with"    4           [3,3,5,2,4]
         * 6th      5      yes              6    "you"     3           [3,3,5,2,4,3]
         * 7th      6      no
         * End Loop
         */
    }

    // 第3步: 通过Math.max()取出数组arrNum中最大值,并且输出
    return Math.max.apply(null, arrNum); // 5
}
Function.apply()是JS的一个OOP特性,一般用来模拟继承和扩展this的用途,对于上面这段代码,可以这样去理解:

XXX.apply是一个调用函数的方法,其参数为:apply(Function, Args),
Function为要调用的方法,Args是参数列表,当Function为null时,默认为上文,
即
Math.max.apply(null, arr)

可认为是
apply(Math.max, arr)
然后,arr是一个参数列表,对于max方法,其参数是若干个数,即
Math.max(a, b, c, d, ...)
当使用apply时,把所有参数加入到一个数组中,即
arr =  [a, b, c, d, ...]
代入到原式,
Math.max.apply(null, [a, b, c, d, ...])
实际上等同于
Math.max(a, b, c, d, ...)
在此处,使用apply的优点是在部分JS引擎中提升性能。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值