常见类型判断

一、判断方法总结

数据举例:

const types = {
  str: 'hello',
  strObj: new String('hello'),
  num: 123,
  bool: true,
  'null': null,
  'undefined': undefined,
  symbol: Symbol(),
  bigInt: 9007199254740991n,
  fun: function () {},
  arr: [],
  obj: {},
  map: new Map(),
  weakMap: new Map(),
  set: new Set(),
  weakSet: new Set()
}

结果统计:

类型typeofinstanceof [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