JS数据类型检验

咱们知道判断数据类型能够用typeof函数

定义一些数据ui

let num=1,str='str',bool=true,obj={},arr=[],sy=Symbol('s'),g,reg=/test/,date=new Date()

typeof运算符this

typeof num //"number"
typeof str //"string"
typeof bool //"boolean"
typeof g //"undefined"
typeof obj //"object"
typeof arr //"object"
typeof reg//"object"
typeof date //"object"
typeof null //"object"

能够看出来typeof 对基本类型(除了null)能够判断出类型,可是对应对象,没有办法知道具体的类型prototype

instanceof 判断是否为每一个类型的实例,经过这个方法能够判断出类型,咱们对上述数据进行判断code

function Person(){}
let p=new Person()
function Foo(){}
let f=new Foo()
num instanceof Number //false 
str instanceof String //false
arr instanceof Object //true
arr instanceof Array //true 
obj instanceof Object //true 
obj instanceof Array //false 
reg instanceof RegExp //true
date instanceof Date //true

constructor对象

arr.constructor ===Array //true 
obj.constructor ===Object //true 
str.constructor === String  //true

从输出的结果咱们能够看出,除了undefined和null,其余类型的变量均能使用constructor判断出类型。
不过使用constructor也不是保险的,由于constructor属性是能够被修改的,会致使检测出的结果不正确继承

Object.prototype.toString.call原型链

Object.prototype.toString.call(str) //"[object String]"

Object.prototype.toString.call(obj) //"[object Object]"

Object.prototype.toString.call(null) //"[object Null]"

Object.prototype.toString.call(num) ///"[object Number]"

...

每一个对象都有一个toString()方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认状况下,toString()方法被每一个Object对象继承。若是此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中type是对象的类型字符串

那为何Object.toString.call(params) 会报错呢?原型

Object.toString.call(num)

Uncaught TypeError: Function.prototype.toString requires that 'this' be a Function at Number.toString (<anonymous>) at <anonymous>:1:17

这是为何呢,由于Object为构造函数,Object构造函数自己没有toString方法。依照原型链关系,Object构造函数的上游原型链是Function.prototype。因此,你调用Object.toString.call(param)本质上是调用Function.prototype.toString.call(param),这里须要的参数类型是函数,因此会报错。

相关文章
相关标签/搜索