Home > Web Front-end > JS Tutorial > Analysis of methods to determine null in JS

Analysis of methods to determine null in JS

高洛峰
Release: 2016-12-06 11:46:09
Original
1466 people have browsed it

The example in this article describes the method of judging null in JS. Share it with everyone for your reference, the details are as follows:

The following is the incorrect method:

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

When exp is undefined, the same result as null will be obtained, although null and undefined are different.

Note: This method can be used when you want to judge null and undefined at the same time.

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

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

Note: This method can be used when you want to judge null, undefined, number zero, and false at the same time.

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 way:

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

typeof exp != "undefined" excludes undefined;

exp != 0 excludes the numbers zero and false.

The simpler and correct method:

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

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


Related labels:
js
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