简体   繁体   English

为什么 javascript 中的“假”为真?

[英]Why is 'false' truthy in javascript?

I understand that an empty string is falsy in javascript and a not-empty string is truthy in javascript.我知道空字符串在 javascript 中是假的,非空字符串在 javascript 中是真的。

However, why is 'false' truthy in javascript, is there anything explicit in the specification?但是,为什么 javascript 中的'false'真,规范中是否有任何明确的内容? Is it a performance issue or are there situations where you would want the string 'false' to represent true ?这是性能问题还是在某些情况下您希望字符串'false'代表true

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.否则结果为真。

Replying to the last part of your question:回复你问题的最后一部分:

Are there situations where you would want the string 'false' to represent true?是否存在您希望字符串 'false' 代表 true 的情况?

Let's consider I am testing for empty strings in my user input.让我们考虑一下我正在测试用户输入中的空字符串。 To achieve that, I issue:为了实现这一点,我发出:

if (!theInput) {
    // Do something.
}

Now do I want that condition to be true if the user enters false in the text box?现在,如果用户在文本框中输入false ,我是否希望该条件为真? Of course, I don't.当然,我不知道。

In Javascript any string that is not empty is truthy.在 Javascript 中,任何不为空的字符串都是真实的。

So, when evaluating any non-empty string results in true even when the string itself is 'false' .因此,在评估任何非空字符串时,即使字符串本身为'false'也会导致true

You can read more about truthy and falsy values.你可以阅读更多关于truthyfalsy值。

If you want to check a string for truthness, you can check it's length.如果你想检查一个字符串的真实性,你可以检查它的长度。

var val = str.length > 0;

The value of a non-empty string is always true.非空字符串的值始终为真。

Boolean(false) returns false Boolean(false)返回 false

Boolean('false') returns true Boolean('false')返回 true

It's by definition.这是根据定义。 It's a string and it is handled as such.它是一个字符串,它是这样处理的。 No matter the meaning of the string.不管字符串的含义。

If your logic would be applied.如果您的逻辑将被应用。 Then how about following examples:那么下面的例子怎么样:

"1+3==2"
"humans have four eyes"

Are they also falsy?他们也是假的吗?

If you consider the Boolean values, false is false and true is true.如果考虑布尔值,则 false 为 false,true 为 true。

Boolean(true) //returns true
Boolean(false) //returns false

But when you are talking about the strings like 'true' and 'false' or any other non-empty string, Javascript will not read them as Booleans and they will be true as all other non-empty strings.但是,当您谈论像“真”和“假”这样的字符串或任何其他非空字符串时,Javascript 不会将它们读取为布尔值,并且它们将像所有其他非空字符串一样为真。

Boolean('true') //returns true
Boolean('false') //returns true
Boolean('blahblahblah') //returns true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM