zoukankan      html  css  js  c++  java
  • js取数组最大值的四种方式


    var arr = [7,2,0,-3,5];
    1.apply()应用某一对象的一个方法,用另一个对象替换当前对象

    var max = Math.max.apply(null,arr);
    console.log(max)

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

    2.call()调用一个对象的一个方法,以另一个对象替换当前对象

    var max1 = Math.max.call(null,7,2,0,-3,5)
    console.log(max1)

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

    3.sort()+reverse()

    //sort()排序默认为升序,reverse()将数组掉个
    var max3 = arr.sort().reverse()[0];
    console.log(max3)

    4.sort()

    //b-a从大到小,a-b从小到大
    var max2 = arr.sort(function(a,b){
    return b-a;
    })[0];
    console.log(max2)

  • 相关阅读:
    [UE4]虚幻引擎的C++环境安装
    [UE4]Drop,扔物品
    [UE4]Grab抓取
    [UE4]抓取准备
    [UE4]用Format Text进行调试
    [UE4]Overlap Event 碰撞事件
    [UE4]Skeletal Mesh的碰撞体
    [UE4]模拟物理
    [UE4]Static Mesh的碰撞体
    [UE4]镜像
  • 原文地址:https://www.cnblogs.com/lguow/p/10070861.html
Copyright © 2011-2022 走看看