在 JavaScript 中, undefined 和 null 是两个特殊的值,用于表示缺失或空值。

undefined 是一个表示未定义或未赋值的原始值。它在以下情况下使用:

1. 变量声明了但未初始化时,默认为 undefined 。

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

2. 访问对象属性或数组元素时,如果该属性或元素不存在,则返回 undefined 。

let obj = { name: "John", age: 30 };console.log(obj.address); // undefinedlet arr = [1, 2, 3];console.log(arr[3]); // undefined

3. 函数没有明确返回值时,默认返回 undefined 。

function foo() {// 没有明确返回值}console.log(foo()); //undefined

相比之下, null 是一个表示空值或没有对象引用的特殊值。它通常由程序员显式赋予变量或属性,表示该值为空。例如:

let x = null;console.log(x); // null

null 主要用于以下情况:

1. 初始化一个变量,以便稍后将其设置为对象。

let obj = null; // 初始化为 nullobj = { name: "John", age: 30 }; // 后续设置为对象

2. 表示函数的参数不具有对象引用。

function foo(arg) {  if (arg === null) {    console.log("参数为空");  } else {    console.log("参数不为空");  }}foo(null); // 参数为空foo("Hello"); // 参数不为空

需要注意的是, undefined 和 null 是不同的类型。 undefined 是一个类型为 undefined 的值,而 null 是一个类型为 object 的值。然而,在相等性比较( == 或 === )中,它们是相等的,因为它们都表示着相同的含义——空值。

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

在编程中,通常使用 undefined 来表示未定义或未赋值的状态,使用 null 来表示有意地将一个值设置为空。

当涉及到 undefined 和 null 的更多细节时,还有一些要注意的事项:

1. 类型检查

– 使用 typeof 操作符检查 undefined 值时,会返回字符串 “undefined” 。
– 使用 typeof 操作符检查 null 值时,会返回字符串 “object” 。这是一个历史遗留问题, null 被错误地标识为对象类型。

let x;console.log(typeof x); // "undefined"let y = null;console.log(typeof y); // "object"

2. 默认参数值

– 当函数的参数没有传递或传递的值为 undefined 时,可以使用默认参数值。
– 当函数的参数传递 null 值时,会将 null 视为有效值,而不会触发默认参数值。

function foo(x = "default") {    console.log(x);}foo(); // "default"foo(undefined); // "default"foo(null); // null

3. 安全导航操作符

– 使用安全导航操作符( ?. )可以避免访问对象属性或调用方法时出现 undefined 或 null 的错误。如果属性或方法不存在,则会返回 undefined 。

let obj = { name: "John", address: { city: "New York" } };console.log(obj.address?.city); // "New York"console.log(obj.address?.zipCode); // undefined

4. 变量赋值:

– 在变量赋值时, undefined 被视为一个变量可以接收的有效值。
– 而 null 被视为一个特殊值,通常用于表示空或未定义的状态。

let x = undefined;console.log(x); // undefinedlet y = null;console.log(y); // null