跳到主要内容

JS 内置类型有哪些?typeof 怎么用?

面试速答(30 秒版 TL;DR)

  • JS 的“内置类型”(数据类型)可以按两类讲:原始类型(primitive)对象(object)
  • 7 种原始类型undefinednullbooleannumberbigintstringsymbol
  • 其余都是 object(包含数组、函数、日期、正则、Map/Set 等)。
  • typeof 主要用来区分原始类型,但对 null 有历史 bug:typeof null === "object"

心智模型:类型(type)和“值的包装”(boxing)要分开

  • 原始值本身不是对象,但在“访问属性/方法”时会发生 装箱(boxing):临时把原始值包装成对应的对象(例如 new String("a") 的语义效果)。
  • 所以你会看到:"a".toUpperCase() 能调用,但 "a" 依然是原始类型的 string

7 种原始类型 + 1 种对象类型

原始类型(primitive)

  • undefined:缺失/未初始化
  • null:刻意的空值
  • booleantrue/false
  • number:IEEE 754 双精度浮点数(既表示小数也表示“可精确表示的整数”)
  • bigint:任意精度整数
  • string:字符串
  • symbol:唯一标识(常用于对象属性 key)

对象(object)

除以上 7 种外,其余都是对象:

  • 普通对象 {}、数组 []、函数 function(){}(函数是可调用对象)
  • 内建对象:DateRegExpMap/SetPromise、各种 TypedArray 等

typeof 的常见结果(面试最常用)

typeof undefined; // "undefined"
typeof null; // "object" (历史遗留)
typeof true; // "boolean"
typeof 1; // "number"
typeof 1n; // "bigint"
typeof "a"; // "string"
typeof Symbol("x"); // "symbol"
typeof {}; // "object"
typeof []; // "object"
typeof function () {}; // "function"

结论:面试回答时建议补一句,“真正判断 nullx === null,判断数组用 Array.isArray(x)。”


典型题 & 标准答法

Q1:JS 到底有几种类型?

  • 规范层面:8 种(7 primitive + object)。
  • 面试口径:一般回答 “7 种原始类型 + 对象”,并点出 typeof null 的坑即可。

Q2:typeof 适合做运行时类型检查吗?

  • 适合区分:undefined/boolean/number/bigint/string/symbol/function
  • 不适合精细区分对象子类型(数组、日期等),需要配合:
Array.isArray(x);
x instanceof Date;
Object.prototype.toString.call(x); // "[object Date]" 等

易错点/坑

  • typeof null"object",但 null 不是对象,不能访问属性:null.x 会抛错。
  • typeof []"object",判断数组要用 Array.isArray
  • new String("a") 是对象,不等于 "a" 这个原始字符串:工程上尽量避免 new String/Number/Boolean

速记要点(可背诵)

  • 7 primitive:undefined null boolean number bigint string symbol
  • 其余都是 object;typeof null 有坑,数组用 Array.isArray