面试题库 词条目录
前端Wiki/面试题库/JavaScript/JS 基础题

数据类型与类型判断

JS 有 8 种数据类型:7 种原始类型(number、string、boolean、null、undefined、symbol、bigint)加 object。区分它们的标准组合是 typeof(判断原始类型)+ instanceof(判断对象的具体类)+ Object.prototype.toString.call()(最准确的类型字符串)。

两个经典坑:typeof null === "object"(历史遗留:null 在底层按对象指针存储);引用类型用 == 比较的是地址,== 的隐式转换规则是面试重灾区。最佳实践:一律用 ===,需要宽松判断空值时显式写 a === null || a === undefined。

  • 8 大类型:7 原始 + object;symbol / bigint 是 ES6 补充
  • typeof 判原始类型,instanceof 判对象继承链,toString.call 是万能答案
  • typeof null === “object” 是历史 bug;比较一律用 ===
JS
// 类型判断三板斧
console.log(typeof 'str');      // string
console.log(typeof 1);          // number
console.log(typeof null);       // object —— 历史遗留 bug
console.log(typeof []);         // object —— 数组分不出来

// 引用类型用 instanceof 或万能 toString
console.log([] instanceof Array);                     // true
console.log(Object.prototype.toString.call(null));    // [object Null]
console.log(Object.prototype.toString.call([]));      // [object Array]

// 手写最稳的类型判断(面试常考)
function typeOf(v) {
  return Object.prototype.toString.call(v).slice(8, -1).toLowerCase();
}
console.log(typeOf(null), typeOf([]), typeOf(/x/), typeOf(Promise.resolve()));
// null array regexp promise

// == 隐式转换陷阱
console.log(null == undefined);  // true(仅此一对)
console.log(0 == false);         // true(都转数字)
console.log('' == 0);            // true
console.log(NaN == NaN);         // false —— NaN 与任何值都不等
本节要点类型判断三件套:typeof 看原始、instanceof 看对象链、toString.call 最准确;比较永远用 ===。
🔗 相关词条JavaScript原型链闭包