跳到主要内容

JavaScript 中的 null 和 undefined

提示
  1. undefined 和 null 的基本概念:在 JavaScript 中,undefined 表示声明了变量但未初始化;而 null 用于表示变量的值为空或未知。
  2. 假值和类型检测undefinednull 都被视为假值。使用 typeof 运算符时,null 返回 "object" 类型,而 undefined 返回 "undefined" 类型。
  3. 在比较和默认参数中的差异:使用 == 运算符时,nullundefined 被视为相等;但使用 === 时,它们不相等。在带有默认参数的函数中,传递 undefined 会触发默认值,而传递 null 则不会。

JavaScript 有 8数据类型,它们是:

数据类型描述
String表示文本数据
Number整数或浮点数
BigInt任意精度的整数
Boolean两个值之一:true 或 false
Object数据的键值对集合
Symbol实例唯一且不可变的数据类型
undefined变量未初始化的数据类型
null表示 null 值的特殊关键字

本教程将讨论 undefinednull 这两种数据类型。

JavaScript 中的 undefined

如果声明了变量但没有赋值,那么该变量的值将为 undefined。例如,

let name;
console.log(name); // undefined

也可以显式地将 undefined 赋值给变量。例如,

let name = "Felix";

// 将 undefined 赋值给 name 变量
name = undefined;

console.log(name); // 返回 undefined

注意: 通常,null 用于为变量赋予“未知”或“空”值。因此,你可以将 null 赋给变量。

JavaScript 中的 null

在 JavaScript 中,null 是一个特殊值,代表 未知的值。例如,

let number = null;

上述代码表明,目前 number 变量为空,稍后可能会有值。

注意null 与 NULL 或 Null 不同。

假值

在 JavaScript 中,undefinednull 被视为假值。例如,

if (null || undefined) {
console.log("null 是真");
} else {
console.log("null 是假");
}

输出

null 是假

当与 Boolean() 函数一起使用时,undefinednull 会转换为 false。例如,

let result;

result = Boolean(undefined);
console.log(result); // false

result = Boolean(null);
console.log(result); // false

JavaScript typeof:null 和 undefined

在 JavaScript 中,null 被视为对象。你可以使用 typeof 运算符 来检查这一点。typeof 运算符用于确定变量和值的类型。例如,

const a = null;
console.log(typeof a); // object

当使用 typeof 运算符确定 undefined 值时,它返回 undefined。例如,

let a;
console.log(typeof a); // undefined

JavaScript 默认值:null 和 undefined

在访问本节之前,请确保查看 JavaScript 默认参数 教程。

在 JavaScript 中,如果向一个带有默认值的函数参数传递 undefined,则 undefined 被忽略,使用默认值。例如,

function test(x = 1) {
console.log(x);
}

// 传递 undefined
// 使用默认值 1
test(undefined); // 1

然而,如果向默认参数函数传递 null,函数会将 null 作为值。例如,

function test(x = 1) {
console.log(x);
}

// 传递 null
// 使用 null
test(null); // null

比较 null 和 undefined

使用等于运算符 == 比较 nullundefined 时,它们被视为相等。例如,

console.log(null == undefined); // true

在 JavaScript 中,== 通过执行 类型转换 来比较值。nullundefined 都返回 false。因此,nullundefined 被认为是相等的。

而,使用严格等于运算符 === 比较 nullundefined 时,结果为 false。例如,

console.log(null === undefined); // false