var arr=[1,231,33,33,9999,9999,9339,1011];
第一种 :sort()
Array.prototype
.max = function() {
return this
.sort(function(a
,b
) {
return a
- b
})[this
.length
- 1]
}
arr
.max() //9999
第二种 : 排序,这里只选排序的冒泡排序为代表
Array.prototype
.max=function() {
var len
=this
.length
;
for(var i
=0; i
<len
-1;i
++){
for(var j
=0;j
<len
-i
-1;j
++){
if(this
[j
]>this
[j
+1]){
var temp
=this
[j
];
this
[j
]=this
[j
+1];
this
[j
+1]=temp
;
}
}
}
return this
[this
.length
-1]
}
arr
.max() //9999
第三种 : 比较
Array.prototype
.max=function(){
var num
=0;
for(var i
=0; i
<this
.length
; i
++){
if(this
[i
]>num
){
num
=this
[i
];
}
}
return num
}
arr
.max() //9999
第四种 : ES6里的reduce()
Array.prototype
.max=function(){
return this
.reduce
(function(init
,item
){
if(init
>=item
){
init
=init
}else{
init
=item
}
return init
})
}
arr
.max() //9999
第五种 : Math.max + apply
Array.prototype
.max=function(){
return Math
.max.apply
(null,this
)
}
arr
.max() //9999
第六种 :Math.max + ES6的扩展运算符(...)
Array.prototype
.max=function(){
return Math
.max(...this
)
}
arr
.max() //9999
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 条评论 - 求数组中的最大值的六种方法