区别数组和对象的三种方法constructor、instance of、Object.prototype.toString.call()

区别数组和对象的三种方法:

① constructor 通过构造函数
② A instance of B 原理上是找A的原型链上有没有B
③ Object.prototype.toString.call() 返回的是//"[object Type]"的形式,可以返回参数的类型

在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number、string、undefined、boolean、object。不包括null。
对于null、array、function、object来说,使用typeof都会统一返回object字符串。
要想区分对象、数组、函数、单纯使用typeof是不行的。在JS中,可以通过Object.prototype.toString方法,判断某个对象之属于哪种内置类型。
分为null、string、boolean、number、undefined、array、function、object、date、math。

这里查看变量arr和变量obj的数据类型:

var arr=[];//arr.constructor Array
var obj={};//obj.constructor Object
//在控制台输入:
--------------------------------------
arr.constructor 
"ƒ Array() { [native code] }"

obj.constructor
"ƒ Object() { [native code] }"
--------------------------------------
[] instanceof Array
"true"
//{} instanceof Object会报错,因为有可能是函数的{},用变量obj 
obj instanceof Object
"true"
--------------------------------------
Object.prototype.toString.call([])
"[object Array]"
Object.prototype.toString.call({})
"[object Object]"
Object.prototype.toString.call(123)
"[object Number]"
Object.prototype.toString.call('123')
"[object String]"
Object.prototype.toString.call(new Date)
"[object Date]"
Object.prototype.toString.call(null)
"[object Null]"
发布了30 篇原创文章 · 获赞 26 · 访问量 7197

猜你喜欢

转载自blog.csdn.net/aaqingying/article/details/95086261
今日推荐