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 }
本文介绍了六种不同的方法来找出数组中的最大值,包括使用数组原型方法、冒泡排序、遍历比较、reduce函数、Math.max应用及扩展运算符。每种方法都附有详细的代码实现,为开发者提供了多样化的选择。
8964

被折叠的 条评论
为什么被折叠?



