JavaScript中的null和undefined有什么区别?

在 JavaScript 中,nullundefined 是两个表示“无”或“缺失”值的特殊类型,但它们在语义和使用上有显著的区别。以下是对这两个值的详细解释及其主要区别。

一、定义

1. null

  • 定义null 是一个表示“无值”或“空值”的对象类型的原始值。它通常表示一个变量已被定义,但没有值。
  • 用法:可以显式地将变量设置为 null,表示该变量当前没有值。
let x = null;
console.log(x); // 输出: null

2. undefined

  • 定义undefined 是一个表示“未定义”的原始值。它表示一个变量已经声明,但尚未赋值。
  • 用法:当一个变量声明后但未被赋值时,JavaScript 会自动将其初始化为 undefined
let y;
console.log(y); // 输出: undefined

二、类型

  • null:属于对象类型(在 JavaScript 中,typeof null 返回 "object")。
  • undefined:属于未定义类型(typeof undefined 返回 "undefined")。
console.log(typeof null);      // 输出: "object"
console.log(typeof undefined);  // 输出: "undefined"

三、相等性比较

1. 使用 ===== 比较

  • ==:在非严格相等比较中,nullundefined 是相等的。
console.log(null == undefined); // 输出: true
  • ===:在严格相等比较中,nullundefined 是不相等的。
console.log(null === undefined); // 输出: false

四、使用场景

1. null 的使用场景

  • 显式赋值:当你希望表示一个变量已定义但没有值时,可以使用 null
let user = null; // 用户尚未登录
  • API 设计:在一些函数中,可以使用 null 来表示缺失的参数或返回值。

2. undefined 的使用场景

  • 未赋值的变量:当声明一个变量但未赋值时,JavaScript 自动赋值为 undefined
let score;
console.log(score); // 输出: undefined
  • 函数返回值:如果一个函数没有返回值,默认返回 undefined
function doSomething() {
    // 没有返回语句
}

console.log(doSomething()); // 输出: undefined

五、总结

特性 null undefined
类型 对象类型(typeof null 返回 "object" 未定义类型(typeof undefined 返回 "undefined"
声明 显式赋值表示“无值” 自动赋值表示“未定义”
相等性 null == undefinedtrue null === undefinedfalse
使用场景 表示已定义但无值的变量 表示未赋值的变量