js如何判断一个对象是数组还是对象

244 阅读1分钟

1、Array.isArray()

Array.isArray([]) //true

ES5将Array.isArray()正式引入JavaScript,目的就是准确地检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的。

2、使用原型链来判断

[].__protp__ === Array.prototype //true
var fun = function(){}
fun.__proto__ === Function.prototype //true

3、使用Object.prototype.toString 来判断是否是数组

Object.prototype.toString.call( [] ) === '[object Array]' //true
Object.prototype.toString.call( function(){} ) === '[object Function]' //true

原型链的方式判断(兼容性好),那为什么是先判断浏览器支不支持Array.isArray()这个方法,如果不支持才使用原型链的方式呢? 原因是Array.isArray()这个方法的执行速度比原型链的方式快了近一倍。