判断JS类型常⽤的三种⽅式
前⾔:判断JS类型,有以下⼏种⽅法:1、typeof 2、String.call 3、instance of。
(⼀)JS的类型
JS的基本类型共有七种:bigInt(bigInt是⼀种内置对象,是处symbol外的第⼆个内置类型)、number、string、boolen、symbol、undefined、null。复杂数据类型有对象(object)包括基本的对象、函数(Function)、数组(Array)和内置对象(Date等)。
(⼆)判断JS的类型
⽅法⼀、typeof⽅法
基本数据类型除了null外都返回对应类型的字符串。
typeof 1 // "number"
typeof 'a'  // "string"
typeof true  // "boolean"
typeof undefined // "undefined"
typeof Symbol() // "symbol"
typeof 42n // "bigint"
注:判断⼀个变量是否被声明可以⽤(typeof 变量 === “undefined”)来判断
null返回“object”
typeof null  // "object"
因为历史遗留的原因。typeof null 尝试返回为null失败了,所以要记住,typeof null返回的是object。
特殊值NaN返回的是 “number”
typeof NaN // "number"
⽽复杂数据类型⾥,除了函数返回了"function"其他均返回“object”
typeof({a:1}) // "object"普通对象直接返回“object”
typeof [1,3] // 数组返回"object"
typeof(new Date) // 内置对象"object"
函数返回"function"
typeof function(){} // "function"
所以我们可以发现,typeof可以判断基本数据类型,但是难以判断除了函数以外的复杂数据类型。于是我们可以使⽤第⼆种⽅法,通常⽤来判断复杂数据类型,也可以⽤来判断基本数据类型。
⽅法⼆、String.call⽅法 ,他返回"[object, 类型]",注意返回的格式及⼤⼩写,前⾯是⼩写,后⾯是⾸字母⼤写。
基本数据类型都能返回相应的类型。
String.call(999) // "[object Number]"
String.call('') // "[object String]"
String.call(Symbol()) // "[object Symbol]"
String.call(42n) // "[object BigInt]"
String.call(null) // "[object Null]"
String.call(undefined) // "[object Undefined]"
String.call(true) // "[object Boolean]
复杂数据类型也能返回相应的类型
String.call({a:1}) // “[object Object]”
String.call([1,2]) // “[object Array]”
typeof array
String.call(new Date) // “[object Date]”
String.call(function(){}) // “[object Function]”
这个⽅法可以返回内置类型
⽅法三、obj instanceof Object ,可以左边放你要判断的内容,右边放类型来进⾏JS类型判断,只能
⽤来判断复杂数据类型,因为instanceof 是⽤于检测构造函数(右边)的 prototype 属性是否出现在某个实例对象(左边)的原型链上。
[1,2] instanceof Array  // true
(function(){}) instanceof Function // true
({a:1}) instanceof Object // true
(new Date) instanceof Date // true
obj instanceof Object⽅法也可以判断内置对象。
缺点:在不同window或者iframe间,不能使⽤instanceof。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。