【问题标题】:Why the boolean false is less than boolean true?为什么布尔假小于布尔真?
【发布时间】:2019-03-24 09:44:15
【问题描述】:

当我想解决 JavaScript* 中的排序问题时,我发现 false Booleantrue Boolean 差。为什么?

我已经尝试了以下内容:

console.log(false < true) //return true
console.log(true < false) //return false

我的问题:

const todos = [{
  text: 'running',
  completed: false
}, {
  text: 'walking',
  completed: true
}, {
  text: 'Studying',
  completed: true
}, {
  text: 'learn javascript',
  completed: false
}, {
  text: 'learn react',
  completed: true
}]

const sortTodos = function(todo) {
  todo.sort(function(a, b) {
    if (a.completed < b.completed) {
      return -1
    } else if (b.completed < a.completed) {
      return 1
    } else {
      return 0
    }
  })
}

sortTodos(todos)
console.log(todos)

【问题讨论】:

  • 因为布尔值 true 被解释为 1,false 被解释为 0

标签: javascript arrays boolean


【解决方案1】:

false 强制转换为 0 另一方面 true 强制转换为 1

console.log(+true)
console.log(+false)

【讨论】:

    【解决方案2】:

    这是因为false 的计算结果为0,而true 的计算结果为1。因为1 &gt; 0true &gt; false,反之亦然。

    【讨论】:

      【解决方案3】:

      类型强制。

      为了评估&gt; 的结果,JS 将布尔值强制转换为数字。真为1,假为0。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-05
        • 2021-07-01
        相关资源
        最近更新 更多