<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>排序</title>
</head>
<body>
</body>
<script>
let a=[3,8,2,5,9,0,4,7,1,34];
a.sort();
console.log(a);//[0, 1, 2, 3, 34, 4, 5, 7, 8, 9]默认的排序
a.sort(function(a,b){
return a-b;
});
console.log(a);// [0, 1, 2, 3, 4, 5, 7, 8, 9, 34],升序排序
a.sort(function(a,b){
return b-a;
});
console.log(a);//[34, 9, 8, 7, 5, 4, 3, 2, 1, 0],降序排序
//数组元素是对象时的排序应用
let cart=[
{name:"phone",price:12000},
{name:"imac",price:18000},
{name:"ipad",price:3200}
];
cart.sort(function(a,b){
return a.price-b.price;
});
console.table(cart);//元素会按price升序排列
</script>
</html>
网友评论