为什么JavaScript中的“假"真相? [英] Why is 'false' truthy in javascript?

查看:120
本文介绍了为什么JavaScript中的“假"真相?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,在javascript中,空字符串是虚假的,而在JavaScript中,非空字符串是真实的.

I understand that an empty string is falsy in javascript and a not-empty string is truthy in javascript.

但是,为什么'false'在javascript中是正确的,规范中是否有明确的内容?是性能问题还是在某些情况下您希望字符串'false'代表true?

However, why is 'false' truthy in javascript, is there anything explicit in the specification? Is it a performance issue or are there situations where you would want the string 'false' to represent true?

推荐答案

回答问题的最后一部分:

Replying to the last part of your question:

在某些情况下,您希望将字符串'false'用作 代表真实吗?

Are there situations where you would want the string 'false' to represent true?

让我们考虑一下我正在测试用户输入中的空字符串.为此,我发出:

Let's consider I am testing for empty strings in my user input. To achieve that, I issue:

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

现在,如果用户在文本框中输入false,我是否希望该条件成立?当然可以.

Now do I want that condition to be true if the user enters false in the text box? Of course, I don't.

这篇关于为什么JavaScript中的“假"真相?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆