var arr = [
{
id: 1,
name: "张三",
score: 100,
},
{
id: 1,
name: "李四",
score: 45,
},
{
id: 1,
name: "王金",
score: 23,
}
]
const compare = (property, desc = "asc") => {
return function (a, b) {
let value1 = a[property], value2 = b[property]
if (desc === "desc") { //降序
return value2 - value1
} else { //升序
return value1 - value2
}
}
}
console.log(arr.sort(compare("score")))

compare方法的第一个参数是待排序的字段名,第二个参数可选,默认是升序,若是降序,则需传入"desc"
单词:
ascending order :升序
descending order :降序
JavaScript数组排序与比较函数
这篇博客介绍了如何使用JavaScript对数组进行排序,特别是利用比较函数`compare`实现升序和降序排列。示例中展示了根据`score`字段对一组对象数组进行排序的方法,对于排序的灵活性和可配置性进行了探讨。
345

被折叠的 条评论
为什么被折叠?



