面试题系列---【js如何判断一个对象是数组】

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

1.typeof操作符

利用typeof除了array和null判断为object外,其他的都可以正常判断

2.instanceof操作符

var arr = [1,2,3,1];
console.log(arr instanceof Array); // true

var fun = function(){};
console.log(fun instanceof Function); // true

3.对象的constructor 属性

var arr = [1,2,3,1];
console.log(arr.constructor === Array); // true
 
var fun = function(){};
console.log(arr.constructor === Function); // true

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

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

这里使用call来使 toString 中 this 指向 obj。进而完成判断 

5.Array.isArray()

Array.isArray([])  ``// true

6.使用 原型链 来完成判断

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

posted on 2021-06-21 23:45  码农小小海  阅读(138)  评论(0编辑  收藏  举报

导航