zoukankan      html  css  js  c++  java
  • 求数组中的最大值的六种方法

    var arr=[1,231,33,33,9999,9999,9339,1011]; 求数组中的最大值

    总结总结了6个方法,排序的就选了个冒泡排序为代表

     1 Array.prototype.getMax1=function(){
     2     return this.sort(function(a,b){
     3         return a-b
     4     })[this.length-1]-0
     5 }
     6 Array.prototype.getMax2=function(){
     7     var len=this.length;
     8     for(var i=0; i<len-1;i++){
     9         for(var j=0;j<len-i-1;j++){
    10             if(this[j]>this[j+1]){
    11                 var temp=this[j];
    12                 this[j]=this[j+1];
    13                 this[j+1]=temp;
    14             }
    15         }
    16     }
    17     return this[this.length-1]-0
    18 }
    19 Array.prototype.getMax3=function(){
    20     var num=0;
    21     for(var i=0; i<this.length; i++){
    22         if(this[i]>num){
    23             num=this[i];
    24         }
    25     }
    26     return num
    27 }
    28 Array.prototype.getMax4=function(){
    29     return this.reduce(function(init,item){
    30         if(init>=item){
    31             init=init
    32         }else{
    33             init=item
    34         }
    35         return init
    36     })
    37 }
    38 Array.prototype.getMax5=function(){
    39     return Math.max.apply(null,this)
    40 }
    41 Array.prototype.getMax6=function(){
    42     return Math.max(...this)
    43 }

    用到 sort( )、排序、for循环迭代、reduce()、Math.max()

  • 相关阅读:
    允许debian wheezy支持IOS7+的iphone.
    openSUSE 国内镜像摘要
    策略模式总结
    顺序串
    WindowState注意事项
    NLP | 自然语言处理
    Using Autorelease Pool Blocks
    NSAutoreleasePool & thread
    oc语言特性
    oc语言基础整理
  • 原文地址:https://www.cnblogs.com/studyshufei/p/9022384.html
Copyright © 2011-2022 走看看