Skip to content

判断 JavaScript 数据类型通用方法 #25

@RicoLiu

Description

@RicoLiu
function getType(obj) {
  let type = typeof obj;
  if (type !== 'object') {
    return type;
  }

  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
}

> getType()
< "undefined"
> getType([])
< "Array"
> getType({})
<"Object"
> getType(1)
< "number"
> getType('')
< "string"
> getType(window)
< "Window"
> getType(document)
< "HTMLDocument"
> getType(/^a/)
< "RegExp"
> getType(() => {})
< "function"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions