什么是正确的运算符<还是&&?

3

我需要根据一个布尔属性对数组中的对象进行排序。我的代码能够运行,但似乎不是最佳实践,而且我也无法弄清楚原因。

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

5
如果你对将布尔值强制转换为数字感到舒适,那么你可以使用return a.completed - b.completed;,因为你的代码已经这样做了。 - Pointy
1
个人而言,我会保留 <,因为我习惯了 js 中的排序方式。或者像 Pointy 建议的那样,使用差异。我认为你关心的是可读性,在我看来这是一个好问题。但是与“大于”进行比较以及 false < true 因为 0 < 1 在 js(和其他语言)中相当习惯用语。这似乎比使用 (not A) AND B 进行多个布尔运算更不令人惊讶。最终,问问自己(或同事),哪个版本更容易理解。 - Pac0
1个回答

5
你可以计算布尔值的差值。减法会将布尔值强制转换为数字。

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 }],
    sortTodos = todos => todos.sort((a, b) => a.completed - b.completed);

sortTodos(todos);
console.log(todos);
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接