一.升序x-y
<script>
var a = [5,10,110,45,265,88,9];
a.sort(function (x, y) {
return x-y;
});
console.log(a);
</script>
二.降序y-x
<script>
var a = [5,10,110,45,265,88,9];
a.sort(function (x, y) {
return y-x;
});
console.log(a);
</script>
例:按年龄从低到高排序,年龄相同时按性别排序
<script>
var a = [
{
name:"张琪",
gender:"男",
age:18
},
{
name:"李颖",
gender:"女",
age:17
},
{
name:"李新宇",
gender:"男",
age:18
},
{
name:"王华",
gender:"女",
age:18
},
{
name:"刘江",
gender:"男",
age:17
}
];
a.sort(function (x,y) {
if(x.age!=y.age)
return x.age-y.age;
else {
if(x.gender=="男")
return 1;
else
return -1;
}
});
console.log(a);
</script>
排序结果为:
0: {name: “李颖”, gender: “女”, age: 17}
1: {name: “刘江”, gender: “男”, age: 17}
2: {name: “王华”, gender: “女”, age: 18}
3: {name: “张琪”, gender: “男”, age: 18}
4: {name: “李新宇”, gender: “男”, age: 18}
三.随机排序
var a = [5,10,110,45,265,88,9];
arr.sort( (a,b)=> Math.random()-0.5);
小结:用sort()方法排序时,大部分情况都应该指定比较函数,这个函数给出的是数组中两个元素比较的办法,函数的返回值必须是正负零。你可以自己制定排序规则,这是sort()方法的强大之处。