<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script>
//为数组拓展排序方法:从大到小
var arr = new Array(5,12,8,9,6,32);
var arr1 =[59,98,56,7,2,3];
//true表示升序,false表示降序
Array.prototype.sort1 = function(bool=true){
for(var i=0;i<this.length-1;i++){
for(var j=0;j<this.length-1-i;j++){
if(bool){
if(this[j]>this[j+1]){
var temp = this[j];
this[j]=this[j+1];
this[j+1]=temp;
}
}else{
if(this[j]<this[j+1]){
var temp = this[j];
this[j]=this[j+1];
this[j+1]=temp;
}
}
}
}
return this;
}
console.log(arr.sort1(false));
console.log(arr1.sort1(true));
console.log(arr.sort1());//默认为true,升序
</script>
</html>
javascript用原型prototype为所有数组都可以进行排序
猜你喜欢
转载自blog.csdn.net/lanseguhui/article/details/81633530
今日推荐
周排行