如何确定变量is undefined
或null
?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但是,如果执行此操作,JavaScript解释器将停止执行。
如何确定变量is undefined
或null
?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但是,如果执行此操作,JavaScript解释器将停止执行。
(null == undefined) // true
(null === undefined) // false
Because === checks for both the type and value. Type of both are different but value is the same.
Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.
You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).
if (x === null || x === undefined) {
// Add your response code here, etc.
}
I run this test in the Chrome console. Using (void 0) you can check undefined:
var c;
undefined
if (c === void 0) alert();
// output = undefined
var c = 1;
// output = undefined
if (c === void 0) alert();
// output = undefined
// check c value c
// output = 1
if (c === void 0) alert();
// output = undefined
c = undefined;
// output = undefined
if (c === void 0) alert();
// output = undefined
In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.
if (var === undefined){
}
if (var === null){
}
if (var === ''){
}
Check all conditions:
if(var === undefined || var === null || var === ''){
}
The easiest way to check is:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
The shortest and easiest:
if(!EmpName ){
// DO SOMETHING
}
this will evaluate true if EmpName is:
您可以使用抽象相等运算符的品质来做到这一点:
if (variable == null){
// your code here.
}
因为null == undefined
为true,所以上面的代码将同时捕获null
和undefined
。
You can only use second one: as it will check for both definition and declaration