1.升序
语法:arr.sort((a,b)=>{
return a-b;
})
var arr = [4,7,1,3,14]; //[1,3,4,7,14]
var res = arr.sort((a,b)=>{
return a-b;
})
console.log(res)//[1,3,4,7,14]
2.降序
语法: arr.sort((a,b)=>{
return b-a
})
var arr = [4,7,1,3,14];
var res = arr.sort((a,b)=>{
return b-a;
})
console.log(res)//[14,7,4,3,1]
排序例子
<script>
var students = [
{name:"zhang",age:20},
{name:"li",age:18},
{name:"wang",age:9},
{name:"chen",age:14},
]
/*
根据年龄升序
根据年龄降序
*/
var result = students.sort((a,b)=>{
return a["age"]-b["age"]
})
console.log(result)
</script>
<button id="like">通过好评排序</button>
<button id="price">通过价格排序</button>
<script>
var like = document.getElementById("like");
var sales = [
{ name: "张三", like: 60, distance: 1000, price: 10 },
{ name: "张三", like: 30, distance: 100, price: 40 },
{ name: "张三", like: 20, distance: 500, price: 6 },
]
/* 升序 */
function addOrder(arr, value) {
if (Array.isArray(arr)) {
var res = arr.sort((a, b) => {
return a[value] - b[value];
})
return res;
}else{
return null;
}
}
like.onclick = function () {
console.log(addOrder(sales, "like"))
}
price.onclick = function () {
console.log(addOrder(sales, "price"))
}
</script>