判断一个变量的类型

1.typeof 能够区分除数组和对象和null外的所有类型

// 根据typeof判断对象不太准确
表达式                       返回值
typeof undefined           'undefined'
typeof null                'object'
typeof true                'boolean'
typeof 123                 'number'
typeof "abc"               'string'
typeof function() {}       'function'
typeof {}                  'object'
typeof []                  'object'

//区分[]和{}

//<1>.判断对象

var obj = {}
var arr = []

1、toString(推荐)

Object.prototype.toString.call(obj) === '[object Object]' //true

Object.prototype.toString.call(arr) === '[object Object]' //false 


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

2、constructor

obj.constructor === Object  //true
[].constructor === Object   //false  
[].constructor === Array   //true 
[] instance of Array       //true
obj instance of Array     // false

注意: instanceof Array 是可以区分数组和对象的
但是instanceof Object不可以,因为:

obj instanceof Object //true
arr instanceof Object //true

扩展:$.isPlainObject() ---jquery提供的方法

    判断指定参数是否是一个纯粹的对象(所谓”纯粹的对象”,就是该对象是通过”{}”或”new Object”创建的。)

//<2>.判断数组

var obj = {}
var arr = []

1、instanceof

obj instanceof Array //false
arr instanceof Array //true

2、Array对象的 isArray方法

 Array.isArray(obj) //false
 Array.isArray(arr) //true

3、Object.prototype.toString

 Object.prototype.toString.call(obj) === '[object Array]'; //false
 Object.prototype.toString.call(arr) === '[object Array]'; //true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值