在Javascript中,我看到使用字符串類型來表示「true」和「false」的代碼。爲什麼不簡單地使用布爾類型?使用布爾類型與字符串類型「true」/「false」有什麼優點和缺點?
在Javascript中使用布爾類型與字符串類型「true」/「false」有什麼優缺點?或者,使用字符串類型來表示布爾值是不是很簡單?
在Javascript中,我看到使用字符串類型來表示「true」和「false」的代碼。爲什麼不簡單地使用布爾類型?使用布爾類型與字符串類型「true」/「false」有什麼優點和缺點?
在Javascript中使用布爾類型與字符串類型「true」/「false」有什麼優缺點?或者,使用字符串類型來表示布爾值是不是很簡單?
字符串"true"
和"false"
被認爲是真的。所以,千萬不要使用它們來代替布爾值。
console.log(Boolean("true"));
# true
console.log(Boolean("false"));
# true
也
console.log(true != "true");
# true
console.log(false != "false");
# true
你應該總是使用布爾值。
使用字符串"false"
作爲布爾值仍然是truthy,因爲它不是空字符串。
Boolean("true")
>> true
Boolean("false")
>> true
Boolean("")
>> false
您應該使用布爾其中possible-其他原因比較布爾是遠遠快於字符串比較來執行。
是的,使用字符串作爲布爾值是不好的做法。 – elclanrs