1,080   JS

数组排序是用到 sort(),发现没达到预期效果,如下图所示

var b=[3,2,11,4,31];
console.log(b.sort());
// [11, 2, 3, 31, 4]

查了 sort() 排序方法才知道,原来是采用字符 Unicode 编码来排序的,所以数字会自动转换为字符串再排序,字符串再按顺序每个字符排序

var a=['bdf','jei','zcv','ajd','aby','aca'];
console.log(a.sort());
// ["aby", "aca", "ajd", "bdf", "jei", "zcv"]

估计为了避免数字排序的问题,sort() 就增加了一个参数 sortby,可以通过函数来更改排序依据,函数例子

function sortByNumber(a,b)
{
return a - b
}

return < 0, a 排在 b 前面 return > 0, a 排在 b 后面
return = 0, 则并排

var b=[3,2,11,4,31];
var asc=function(a,b){
	return a-b;
}
var desc=function(a,b){
	return b-a;
}
console.log(b.sort(asc));
console.log(b.sort(desc));




Leave a Reply

Your email address will not be published. Required fields are marked *