目录
instanceof和constructor的判定也存在一些弊端
第四种:通过Object.prototype.toString.call()判断
第一种:Array.isArray
原理:Array.isArray()用于确定传递的值是否是一个数组,返回一个布尔值
const arr = [1,2,3,4] console.log(Array.isArray(arr)); // true
有个问题是Array.isArray()是ES5新增的方法,目的就是提供一个稳定可用的数组判断方法,对于ES5之前不支持此方法的问题,我们其实可以做好兼容进行自行封装,如下:
第二种:instanceof
原理:instanceof运算符用于检验构造函数的Array.prototype属性是否出现在对象的原型链中的任何位置,返回一个布尔值
const arr1=[1,2,3,4]; console.log(arr1 instanceof Array);
看下图:
第三种:通过constructor判断
原理:实例的构造函数属性constructor指向构造函数,通过constructor属性可以判断是否为一个数组
const arr = [1, 2, 3, 4] console.log(arr.constructor === Array); // true console.log(arr.__proto__.constructor === Array); //true
instanceof和constructor的判定也存在一些弊端
instanceof和constructor的判定也存在一些弊端,他们判定的数组必须定义在同一个页面,否则将会判定为false。
如果在iframe中的数组判定,就会出错。
第四种:通过Object.prototype.toString.call()判断
原理:Object.prototype.toString.call()可以获取到对象的不同类型
let arr = [1, 2, 3, 4] console.log(Object.prototype.toString.call(arr) === '[object Array]'); // true
对象的toString方式也可以判定数组类型,一般来说这种方式的判定是各大库的一种Array.isArray的代替实现。
例如,polyfill中,就是如此实现:
if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } const arr = [1, 2, 3, 4] Object.prototype.toString.call(arr) === '[object Array]' // true
let arr = [1,2,3,4]; console.log(Object.prototype);//完整的原型对象 console.log(Object.prototype.toString);//f toString() {[native code]} 代表这是一个函数 console.log(Object.prototype.toString());//[object Object] 执行了上面的函数 //通过Object.prototype.toString 这个函数作为父类,调用父类.call(子类)方法初始化子类 console.log(Object.prototype.toString.call(arr));//[object Array]
5.补充:typeof
typeof 只能检测 基本数据类型,包括boolean、undefined、string、number、symbol,而null ,Array、Object ,使用typeof出来都是Object,函数的typeof 是function 无法检测具体是哪种引用类型。
console.log(typeof(100),'1'); console.log(typeof("name"),'2'); console.log(typeof(true),'3'); console.log(typeof(null),'4'); console.log(typeof(undefined),'5'); console.log(typeof([]),'6'); console.log(typeof(Function),'7');
总结
由上述几个方法判定,可以得出,其实polyfill的判定是最合理的,也最具有兼容性的一种判定。
利用toString判定,胜出。
面试题31:JS中判断是数组的四种方法
于 2022-05-10 11:38:16 首次发布