← 返回完整题库
JavaScript简单

JavaScript 中检测数据类型有哪些方式?

参考答案

  1. typeof:基本类型 / function;typeof null === 'object'
  2. Object.prototype.toString.call(x):精确分类([object Date] 等)
  3. instanceof:引用类型与继承链(跨 realm 失效)
  4. constructor:可被改写,不可靠
  5. Array.isArray(x):数组专用,跨 realm 可靠
  6. Number.isNaN / Number.isFinite / Number.isInteger
  7. 自定义:Symbol.toStringTag、业务 type 字段
  8. x === null、typeof x === 'object' && !x

推荐:typeof(基本类型) + toString(细分) + isArray(数组)。

本题来自 计算机知识面试题库,共 921 道题。