在使用javascript的if语句中使用字符串作为布尔值是否存在任何缺陷?

在使用javascript的if语句中使用字符串作为布尔值是否存在任何缺陷?,javascript,Javascript,假设我们有一个字符串: strTest = "Hello! I am string going to be tested in if statement."; if (strTest) { document.write("I am string and I am not empty."); } else { document.write("I am string and I am empty"); } 如果我们在if语句中使用字符串作为

假设我们有一个字符串:

    strTest = "Hello! I am string going to be tested in if statement.";

    if (strTest) {
      document.write("I am string and I am not empty.");
    } else {
      document.write("I am string and I am empty");
    }

如果我们在if语句中使用字符串作为布尔值,是否有任何缺陷?

如果您只想知道字符串中是否有任何值

if(string)
太好了

如果您需要专门检查未定义的空字符串或假字符串,则会发现您的缺陷

这是另一个解决方案,它确切地告诉您字符串是空的、未定义的还是声明为false的

var strTest = "Hello! I am string going to be tested in if statement.";


if (typeof strTest == 'undefined') {
    document.write("I am undefined.");
} else {
    if (strTest == "false") {
        document.write("I am declared as false.");
    } else {
        var length = strTest.length;
        if (length != 0) {    
            document.write("I am string and I am not empty.");
        } else {
            document.write("I am string and I am empty");

        }
    }
}

不,如果您刚刚知道,任何字符串在
if
中都将被视为true,空字符串除外。如果要测试字符串是否为空,则不会。如果strTest为任何假值,则else块将执行,不一定是空字符串,因此消息可能是“如果我是字符串,我是空的”。@RobG。。。你能写一个例子来支持你的观点吗。我认为,即使双引号中有NULL或FALSE,若语句为true,“NULL”并不是一个假值,
NULL
是。关键是,您并不是专门测试空字符串,而是测试任何错误的值。如果它的类型恰好是string,那么它就是一个空字符串。但是如果它的类型是number,那么它就是
0
。谢谢Felix,但问题是,如果所讨论的代码可以正常工作,为什么我还要编写额外的代码?有问题的代码中真的有缺陷吗?如果
typeof strTest==“undefined”
那么您的设置
var length=strTest.length引发异常类型错误:无法读取未定义的属性“length”