Array.sort()默认都是进行字符串比较,哪怕是数字也会先转换成字符串,然后一个字符一个字符的比较。 const arr = [1, 2, 3 ,10, 12] console.log(arr.sort()); // [1, 10, 12, 2, 3]
比较数字
const compare1 = function(val1
, val2
){
return val1
- val2
}
console
.log(arr
.sort(compare1
));
const compare2 = (val1
, val2
) => {return val2
- val1
}
console
.log(arr
.sort(compare2
));
比较对象
function createComparisonFunction(propertyName
){
return function(obj1
, obj2
){
var value1
= obj1
[propertyName
];
var value2
= obj2
[propertyName
];
if(value1
< value2
){
return -1;
}else if(value1
> value2
){
return 1;
}else{
return 0;
}
}
}
const compare3
= createComparisonFunction('age');
function person(age
){
this.age
= age
;
}
const p1
= new person(11);
const p2
= new person(2);
const p3
= new person(33);
const arr
= [p1
, p2
, p3
];
console
.log(arr
.sort(compare
));