判断对象和数组的区别
不能通过数组的length属性去判断,因为对象中可以传名为length的键值对
判断数组
原文链接:https://blog.csdn.net/qq_34295211/article/details/88306925
let arr = []
-
instanceof
arr instanceof Array
-
__proto__
arr.__proto__ === Array.prototype
-
constructor
arr.constructor === Array
-
Object.prototype.toString
Object.prototype.toString.call(arr) === '[object Array]'
-
Array.isArray
Array.isArray(arr)
其中
方法1,2,3 主要是通过原型去判断的,
4是通过object类型的副属性class去判断的,其中函数的class是Function,结果是[object Function], 普通的对象是Object,结果是[object Object],在js中一个对象一旦被创建,在内部会携带创建对象的类型名,一旦创建就不能被修改了。那么怎么获取这个对象的类型名呢?js中提供了,调用对象原型中的toString方法, Object.prototype.toString.call(obj);因为很多对象继承的toString()方法被重写了,为了能够调用正确的toString()版本,也就是最原始的版本。可以使用Function.call()的方法,其中call可以这么理解,相当于obj去借用这个 Object.prototype.toString();
5是es5新增的方法,最简单
判断对象
原文链接:https://blog.csdn.net/zhangjing0320/article/details/81230170
var obj = {};
1、toString(推荐)
Object.prototype.toString.call(obj) === '[object Object]'
2、constructor
obj.constructor === Object
3、instanceof 需要注意的是由于数组也是对象,因此用 arr instanceof Object 也为true。
obj instanceof Object
4、typeof
typeof obj === Object
// 根据typeof判断对象也不太准确
表达式 返回值
typeof undefined 'undefined'
typeof null 'object'
typeof true 'boolean'
typeof 123 'number'
typeof "abc" 'string'
typeof function() {} 'function'
typeof {} 'object'
typeof [] 'object'
5、$.isPlainObject()
判断指定参数是否是一个纯粹的对象(所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的。)
$.isPlainObject(obj)