Home > Web Front-end > JS Tutorial > How to determine null value using js

How to determine null value using js

小云云
Release: 2017-11-18 16:00:04
Original
3445 people have browsed it

We often judge a null value when developing, so how should we judge it? This article will teach you how to use js to determine the null value. Two methods are used to compare how to correctly use js to determine the null value.

The following is an incorrect approach:

var exp=null;
if(exp==null){
    alert("is null");
}
Copy after login

When exp is undefined, you will also get the same result as null, although null and undefined are different.

Note: When you want to judge null and undefined at the same time, you can use the above method.

var exp=null;
if(!exp){
    alert("is null");
}
Copy after login

If exp is undefined, or the number zero, or false, the same result as null will be obtained, although null is different from the two.

Note: If you want to judge null, undefined, number zero, and false at the same time, you can use the above method.

var exp=null;
if(typeof exp=="null"){
    alert("is null");
}
Copy after login

For backward compatibility, when exp is null, typeof null always returns object, so it cannot be judged this way.

var exp=null;
if(isNull(exp)){
    alert("is null");
}
Copy after login

There is the IsNull function in VBScript, but not in JavaScript.

The following is the correct method:

var exp=null;
if(!exp && typeof exp!="undefined" && exp!=0){
    alert("is null");
}
Copy after login

typeof exp!="undefined" excludes undefined

exp!=0 excludes Number zero and false.

Simpler and correct method:

var exp=null;
if(exp===null){
    alert("is null");
}
Copy after login

Nevertheless, in DOM applications, we generally only need to use (!exp) to judge, because in DOM applications, it may return null may return undefined. If you specifically judge whether null or undefined, the program will be too complicated.

The above is how to use js to determine null. I hope it will be helpful to everyone.

Related recommendations:

Why does JavaScript have null? (Translation) - Tianbeiya

What is the original design intention of null and undefined in js

How to use MySQL database to determine NULL The result is 1?

The above is the detailed content of How to determine null value using js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template