我不知道在js中返回1或-1在array.sort中意味着什么。
const hola = [0, 4, 10, 60, 5]
const holaSorted = hola.sort(function(a,b) {
if (a>b) {
return -1;
} else {
return 1;
}
});
console.log(holaSorted);Console.table(HolaSorted);
60、10、5、4、0
发布于 2019-05-11 00:10:24
首先,如上所述,MDN排序描述非常好。
但我们可以在这里简化:
当我们调用sort时,它允许我们在任何给定的时间提供一个function来计算array的两个elements。
function应该返回:
negative值为a < bpositive值为a > b0 if a === b.然后,sort函数将使用该值分别对这两个元素进行排序。
// Number ordering is very straight forward.
const hola = [0, 4, 10, 60, 5]
const holaSorted = hola.sort((a,b) => a-b);
console.log(holaSorted);
// reverse the order.
const holaSorted2 = hola.sort((a,b) => b-a);
console.log(holaSorted);
但并不是所有的东西都是简单的数字,我们通常希望对对象进行排序,这是提供自定义评估器的更重要的地方。
下面我们使用name进行排序,我们需要根据字符串比较传回1 || -1 || 0。
const people = [
{
name: 'Bob',
age: 20
},
{
name: 'Anne',
age: 50,
},
{
name: 'Terry',
age: 5
}
];
// Order by name
const byName = people.sort((a,b) => (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0);
console.log(byName);
// Order by age
const byAge = people.sort((a, b) => a.age-b.age);
console.log(byAge);
https://stackoverflow.com/questions/56085083
复制相似问题