如何确定变量是“未定义"还是“空"? [英] How can I determine if a variable is 'undefined' or 'null'?

查看:33
本文介绍了如何确定变量是“未定义"还是“空"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何判断变量是undefined还是null?

我的代码如下:

var EmpName = $("div#esd-names div#name").attr('class');if(EmpName == '未定义'){//做点什么};

<div id="名称"></div>

但是如果我这样做,JavaScript 解释器就会停止执行.

解决方案

您可以使用 抽象相等运算符来做到这一点:

if (variable == null){//你的代码在这里.}

因为null == undefined为真,上面的代码会同时捕获nullundefined.

How do I determine if variable is undefined or null?

My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};

<div id="esd-names">
  <div id="name"></div>
</div>

But if I do this, the JavaScript interpreter halts execution.

解决方案

You can use the qualities of the abstract equality operator to do this:

if (variable == null){
    // your code here.
}

Because null == undefined is true, the above code will catch both null and undefined.

这篇关于如何确定变量是“未定义"还是“空"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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