js判断undefined、null

本文详细探讨了JavaScript中null与undefined的区别,并提供了如何准确判断一个变量是否为null或undefined的有效方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

if (!undefined) {
  console.log('undefined is false');
}
// undefined is false

if (!null) {
  console.log('null is false');
}
// null is false

if (!0) {
  console.log('0 is false');
}
// null is false

if (undefined == null) {
  console.log(true);
}
// true

if (undefined === undefined ) {
  console.log(true);
}
// true

if (null === null) {
  console.log(true);
}
// true

通过上面的知识点,我们来看下面的做法:

js判断undefined

以下是不正确的做法:

var a = undefined;
if (a == undefined) {
  console.log("undefined");
}

由前言的知识可知,null==undefined成立,所以这种情况不排除a是null,当然如果要检测一个变量是否为null或undefined可以用这种方法。

以下是正确的作法:

//方法一
var a = undefined;
if (a === undefined) {
  console.log("undefined");
}
//方法二
var a = undefined;
if (typeof(a) == "undefined") {
  alert("undefined");
}

来说一下方法二:typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined",所以可以用此方法,注意不要写成if (typeof(a) == undefined)

js判断null

以下是不正确的做法:

var a = null;
if (a == null) {
  console.log("null");
}

 同理(同js判断undefined的不正确方法)。

var a = null;
if (!a) {
  console("null");
}

该方法不排除a是0或者undefined。

var a = null;
if (typeof(a) == "null") {
  console.log("null");
}

typeof 返回六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined",不包括"null"。

 

以下是正确的作法:

var a = null;
if (!a && typeof(a)!="undefined" && a!=0) {
  console.log("null");
} 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值