JS sort的排序及使用以及原理
程序员文章站
2024-02-23 08:23:04
...
## 一 、升序排列:
var arr=[6,5,4,3,2,1];
arr.sort(
function(n1,n2){
return n1-n2;
});
console.log(arr);//[1,2,3,4,5,6]
## 二、降序排列
var arr=[6,5,4,3,2,1];
arr.sort(
function(n1,n2){
return n2-n1; //升降序变化位置
});
console.log(arr);//[1,2,3,4,5,6]
## 三、根据参数属性值排序
var arr = [
{name:'aaa',age:0},
{name:'bbb',age:17},
{name:'ccc',age:9}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age'))) //[0,9,17]
## 四、根据参数属性值排序
var arr = [
{name:'aaa',age:0},
{name:'bbb',age:17},
{name:'ccc',age:9}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age'))) //[0,9,17]
五、不用sort进行排序
原理和sort排序一样
var arr1= [4,3,2,1]
var arr2 = [1,2,3,4]
//规则1,升序
function rule1 (a,b) {
return a-b
}
//规则2,倒序
function rule2 (a,b) {
return b-a
}
//注:方法sortArray 类似sort,可以传递两个参数数组和规则,array,func
function sortArray (array,func){// array 需要排序的数组 func 排序的规则
var temp;
for(var i = 0;i<array.length;i++){
for(var j = 0;j<array.length-1;j++){
var status = func(array[j],array[j+1])
if(status>0){
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
}
}
console.log(array)
}
return array
}
//下面是调用
var newarr1 = sortArray(arr1,rule1)
console.log(newarr1)
var newarr2 = sortArray(arr2,rule2)
console.log(newarr2)