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