一、方法
1. instanceof
instanceof 的内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。
使用 instanceof判断一个对象是否为数组,instanceof 会判断这个对象的原型链上是否会找到对应的 Array 的原型,找到返回 true,否则返回 false。
1
2[] instanceof Array; // true
但 instanceof 只能用来判断对象类型,原始类型不可以。
注:并且所有对象类型 instanceof Object 都是 true。
[] instanceof Object; // true
2.constructor
在W3C定义中的定义:constructor 属性返回对创建此对象的数组函数的引用,就是返回对象相对应的构造函数。从定义上来说跟instanceof不太一致,但效果都是一样的。
1
2
3let arr= [1,2] arr.constructor === Array //true
3. Object.prototype.toString.call()
每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object type],其中 type 为对象的类型。但当除了 Object 类型的对象外,其他类型直接使用 toString 方法时,会直接返回都是内容的字符串,所以我们需要使用call或者apply方法来改变toString方法的执行上下文。
1
2
3
4
5
6
7
8
9
10const a = ['Hello','An']; a.toString(); // "Hello,An" const b = new Date() console.log(b) //Fri Dec 13 2019 19:43:27 GMT+0800 (中国标准时间) b.toString() //"Fri Dec 13 2019 19:43:27 GMT+0800 (中国标准时间)" let obj = {"a":'1',"b":"2"} obj.toString() //"[object Object]"
Object.prototype.toString.call(an); // “[object Array]”
这种方法对于所有基本的数据类型都能进行判断,即使是 null 和 undefined 。
1
2
3
4
5
6
7
8
9Object.prototype.toString.call('An') // "[object String]" Object.prototype.toString.call(1) // "[object Number]" Object.prototype.toString.call(Symbol(1)) // "[object Symbol]" Object.prototype.toString.call(null) // "[object Null]" Object.prototype.toString.call(undefined) // "[object Undefined]" Object.prototype.toString.call(function(){}) // "[object Function]" Object.prototype.toString.call({name: 'An'}) // "[object Object]" Object.prototype.toString.call() 常用于判断浏览器内置对象时。
4. Array.isArray()
功能:用于确定传递的值是否是一个 Array。如果值是 Array,则为true, 否则为false。
1
2
3
4
5Array.isArray([1,2]); //true Array.isArray({foo: 123}); //false Array.isArray("foobar"); //false Array.isArray(undefined); //false
二、区别
1、Array.isArray() 与 instanceof
当检测Array实例时, Array.isArray
优于 instanceof
,因为Array.isArray
能检测iframes
.
1
2
3
4
5
6
7
8
9
10
11var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array.isArray(arr); // true Object.prototype.toString.call(arr); // true // Considered harmful, because doesn't work though iframes arr instanceof Array; // false
2、Array.isArray() 与 Object.prototype.toString.call()
Array.isArray()是ES5新增的方法,当不存在 Array.isArray() ,可以用 Object.prototype.toString.call() 实现。
1
2
3
4
5
6if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }
参考链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
最后
以上就是美丽自行车最近收集整理的关于数组-判断数组的方法及他们的区别和优劣的全部内容,更多相关数组-判断数组内容请搜索靠谱客的其他文章。
发表评论 取消回复