null

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

null 值表示有意地缺失任何对象值。它是 JavaScript 的原始值之一,在布尔操作中被视为假值

试一试

function getVowels(str) {
  const m = str.match(/[aeiou]/gi);
  if (m === null) {
    return 0;
  }
  return m.length;
}

console.log(getVowels("sky"));
// Expected output: 0

语法

js
null

描述

null 是用字面量 null 写入的。null 不是全局对象属性的标识符,不像undefined。相反,null 表示缺乏标识,表明一个变量没有指向任何对象。在 API 中,当预期有对象但没有相关对象时,常常会检索到 null

js
// foo does not exist. It is not defined and has never been initialized:
foo; // ReferenceError: foo is not defined
js
// foo is known to exist now but it has no type or value:
const foo = null;
foo; // null

示例

nullundefined 的区别

在检查 nullundefined 时,请注意相等 (==) 和全等 (===) 运算符之间的区别,因为前者会执行类型转换。

js
typeof null; // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
Number.isNaN(1 + null); // false
Number.isNaN(1 + undefined); // true

规范

规范
ECMAScript® 2026 语言规范
# sec-null-value

浏览器兼容性

另见