为什么 'false' 在 javascript 中是真实的?
Why is 'false' truthy in javascript?
我知道空字符串在 javascript 中是假的,非空字符串在 javascript 中是真值。
但是,为什么 'false'
在 javascript 中是真实的,规范中有什么明确的内容吗?这是性能问题还是在某些情况下您希望字符串 'false'
代表 true
?
在 Javascript 中,任何不为空的字符串都是真实的。
因此,即使字符串本身是 'false'
.
,在计算任何非空字符串时也会得到 true
您可以阅读有关 truthy and falsy 值的更多信息。
如果你想检查一个字符串的真实性,你可以检查它的长度。
var val = str.length > 0;
非空字符串的值始终为真。
Boolean(false)
returns 错误
Boolean('false')
returns 真
is there anything explicit in the specification?
Yes:
The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
回复你问题的最后一部分:
Are there situations where you would want the string 'false' to
represent true?
假设我正在测试用户输入中的空字符串。为此,我发出:
if (!theInput) {
// Do something.
}
现在,如果用户在文本框中输入 false
,我是否希望该条件为真?我当然不知道。
这是定义。它是一个字符串,它是这样处理的。不管字符串是什么意思。
如果你的逻辑会被应用。那么下面的例子怎么样:
"1+3==2"
"humans have four eyes"
它们也是假的吗?
如果考虑布尔值,假就是假,真就是真。
Boolean(true) //returns true
Boolean(false) //returns false
但是当你谈论 'true' 和 'false' 或任何其他非空字符串时,Javascript 不会将它们读作布尔值,它们将是 true所有其他非空字符串。
Boolean('true') //returns true
Boolean('false') //returns true
Boolean('blahblahblah') //returns true
我知道空字符串在 javascript 中是假的,非空字符串在 javascript 中是真值。
但是,为什么 'false'
在 javascript 中是真实的,规范中有什么明确的内容吗?这是性能问题还是在某些情况下您希望字符串 'false'
代表 true
?
在 Javascript 中,任何不为空的字符串都是真实的。
因此,即使字符串本身是 'false'
.
true
您可以阅读有关 truthy and falsy 值的更多信息。
如果你想检查一个字符串的真实性,你可以检查它的长度。
var val = str.length > 0;
非空字符串的值始终为真。
Boolean(false)
returns 错误
Boolean('false')
returns 真
is there anything explicit in the specification?
Yes:
The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
回复你问题的最后一部分:
Are there situations where you would want the string 'false' to represent true?
假设我正在测试用户输入中的空字符串。为此,我发出:
if (!theInput) {
// Do something.
}
现在,如果用户在文本框中输入 false
,我是否希望该条件为真?我当然不知道。
这是定义。它是一个字符串,它是这样处理的。不管字符串是什么意思。
如果你的逻辑会被应用。那么下面的例子怎么样:
"1+3==2"
"humans have four eyes"
它们也是假的吗?
如果考虑布尔值,假就是假,真就是真。
Boolean(true) //returns true
Boolean(false) //returns false
但是当你谈论 'true' 和 'false' 或任何其他非空字符串时,Javascript 不会将它们读作布尔值,它们将是 true所有其他非空字符串。
Boolean('true') //returns true
Boolean('false') //returns true
Boolean('blahblahblah') //returns true