跳到主要内容

1 篇博文 含有标签「object」

查看所有标签

· 阅读需 2 分钟

JS 数据类型

8种:数字(number)、字符串(string)、布尔(boolean)、空(null)、未定义(undefined)、对象(object)、bigintsymbol

除 object 外,都属于原始数据类型

Typeof

优点:能够快速区分基本数据类型 (以及 function)

缺点:不能将 Object、Array、Null、Map 等引用类型区分,统一返回 object

typeof 1                        // number
typeof true // boolean
typeof 'str' // string
typeof Symbol('') // symbol
typeof undefined // undefined
typeof 1n // bigint
typeof function(){} // function

typeof [] // object
typeof {} // object
typeof null // object

Instanceof

优点:能够区分 Array、Object 和 Function 等引用数据类型,适合用于判断自定义类的实例对象

缺点:不能很好判断原始数据类型(number string boolean bigInt 等)

当使用字面量创建原始类型的值时,它们不是对象,也就不是构造函数的实例。原始类型的值在需要的时候会被自动包装成对应的对象类型(String, Number, Boolean),但这种自动包装并不影响 instanceof 运算符的行为

[] instanceof Array                     // true
function(){} instanceof Function // true
{} instanceof Object // true

1 instanceof Number // false
true instanceof Boolean // false
'str' instanceof String // false

Object.prototype.toString.call()

优点:精准判断数据类型

缺点:写法繁琐不容易记,推荐进行封装后使用

var toString = Object.prototype.toString
toString.call(1) //[object Number]
toString.call(true) //[object Boolean]
toString.call('str') //[object String]
toString.call([]) //[object Array]
toString.call({}) //[object Object]
toString.call(function(){}) //[object Function]
toString.call(undefined) //[object Undefined]
toString.call(null) //[object Null]
toString.call(2n) //[object BigInt]