如何在Javascript中测试null值条件

How to test the null value condition in Javascript?

本文关键字:null 条件 测试 Javascript      更新时间:2023-09-26

下面是代码,

<p id="sayHello"></p>
<script type="text/javascript">
    var yourName = window['prompt']("What is your name?");
    if (yourName != null) {
        window['document']['getElementById']("sayHello").innerHTML = "Hello " + yourName;
    } else {
        window['alert']("Please enter your name next time");
    }
</script>

其中else块需要基于prompt中给出的输入来执行。

prompt框中应该输入什么来测试基元类型Nullnull值?

当您在提示框上单击取消时,else块将被执行。

根据MDN窗口。编译文档:

如果用户在没有输入任何文本的情况下单击"确定",则返回一个空字符串。

因此,您确实希望检查if (yourName !== null && yourName !== ""),因为提示确实返回了空字符串(因此导致else子句执行错误,因为它通过了非空检查)。

我认为您实际上在寻找空字符串。null也是基元值&null表示一个"空"值,即不存在对象值。因此,为了检查null,我们可以使用

if(somVar === null && typeof somVar ==='object')

所以你可以安排你的代码作为

var yourName = window['prompt']("What is your name?");
if (yourName === null & typeof(yourName) ==='object') {
       alert("Please enter your name next time");
    } else {
       document.getElementById("sayHello").innerHTML = "Hello " + yourName; 
    }

还要注意,这将ONLY测试null,并且不会通过"",undefined,false,0&NaN。除了有任何理由使用之外

window['document']['getElementById']("sayHello")

什么时候可以像一样完成

  document.getElementById("sayHello").innerHTML 

如果您正在检查空字符串,那么您还必须验证输入不是空

演示