JavaScript 中检测数据类型有哪些方式?
参考答案
typeof:基本类型 / function;typeof null === 'object'Object.prototype.toString.call(x):精确分类([object Date]等)instanceof:引用类型与继承链(跨 realm 失效)constructor:可被改写,不可靠Array.isArray(x):数组专用,跨 realm 可靠Number.isNaN/Number.isFinite/Number.isInteger- 自定义:
Symbol.toStringTag、业务type字段 x === null、typeof x === 'object' && !x
推荐:typeof(基本类型) + toString(细分) + isArray(数组)。