Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - 如何确定变量是“未定义”还是“空”?(How to determine if variable is 'undefined' or 'null'?)

How do I determine if variable is undefined or null ?

(如何确定变量是否undefined或为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.

(但是,如果执行此操作,JavaScript解释器将停止执行。)

  ask by sadmicrowave translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 .

(因为null == undefined为true,所以上面的代码将捕获nullundefined 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...