首页 > 编程语言 > 详细

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

时间:2021-06-22 09:38:55      阅读:27      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/chenhaiyun/p/14916493.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!