我需要根据一个布尔属性对数组中的对象进行排序。我的代码能够运行,但似乎不是最佳实践,而且我也无法弄清楚原因。
const todos = [{
text: 'Check emails for the day',
completed: true
},{
text: 'Walk the dog',
completed: true
},{
text: 'Go to the store for groceries',
completed: false
},{
text: 'Pick up kids from school',
completed: false
},{
text: 'Do online classes',
completed: false
}]
const sortTodos = function (todos) {
todos.sort(function (a,b) {
if (a.completed < b.completed) { // (or) a.completed === false && b.completed === true
return -1
} else if (b.completed < a.completed){ // (or) !b.completed && a.completed
return 1
} else {
return 0
}
})
}
sortTodos(todos)
console.log(todos)
(b.completed < a.completed){ // (or) !b.completed && a.completed
return a.completed - b.completed;
,因为你的代码已经这样做了。 - Pointy<
,因为我习惯了 js 中的排序方式。或者像 Pointy 建议的那样,使用差异。我认为你关心的是可读性,在我看来这是一个好问题。但是与“大于”进行比较以及false < true
因为0 < 1
在 js(和其他语言)中相当习惯用语。这似乎比使用(not A) AND B
进行多个布尔运算更不令人惊讶。最终,问问自己(或同事),哪个版本更容易理解。 - Pac0