![](/img/trans.png)
[英]Why does the following JS boolean logic fail for everything other than where effectiveDateSelected = true and throughDateSelected = false
[英]Why the boolean false is less than boolean true?
當我想解決JavaScript *中的排序問題時,我發現錯誤的布爾值比真正的布爾值更糟 。 為什么?
我嘗試了以下內容:
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)
另一方面,將false
強制強制為0
,將true
強制強制為1
console.log(+true) console.log(+false)
鍵入強制。
為了評估>
的結果,JS將布爾值強制為數字。 真為1,假為0。
這是因為false
值為0
, true
值為1
。 因為1 > 0
,所以true > false
,反之亦然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.