常见类型判断
一、判断方法总结
数据举例:
结果统计:
类型 | typeof | instanceof [constructor] | Object.prototype.toString.call |
---|---|---|---|
string | "string" | false | "[object String]" |
number | "number" | false | "[object Number]" |
boolean | "boolean" | false | "[object Boolean]" |
null | "object" | false | "[object Null]" |
undefined | "undefined" | false | "[object Undefined]" |
symbol | "symbol" | false | "[object Symbol]" |
object | "object" | true | "[object Object]" |
bigint | "bigint" | false | "[object BigInt]" |
function | "function" | true | "[object Function]" |
array | "object" | true | "[object Array]" |
map | "object" | true | "[object Map]" |
weakMap | "object" | true | "[object WeakMap]" |
set | "object" | true | "[object Set]" |
weakSet | "object" | true | "[object WeakSet]" |
总结:
Object.prototype.toString.call
是通用判断方法(万金油😂),可以作为兜底方案其他推荐判断方式:
基本数据类型(除了null)、BigInt :用
type of
判断null:用
Object.prototype.toString.call
判断函数:优先用
type of
Array:优先使用
Array.isArray
Object:精准判断用
Object.prototype.toString.call
Map、WeakMap、Set、WeakSet:优先使用
instanceof
二、应用:深拷贝
深拷贝主要考查:类型判断 + 递归
Last updated