判断是否数组的方法

instanceof  运算符用来测试一个对象在其原型链中是否存在一个构造函数的prototype属性。

constructor

Object.prototype.toString

isArray

举例

const arr = [1,2,3,4];

arr instanceof Array

// true

arr.constructor ===Array

// true

以上两种判断方法都非常的方便,但是如果是在多个frame中的话是无法判断成功的,因为每个iframe都有自己的执行环境,不共享原型链,因此在为大家推荐两种方法

Object.prototype.toString.call(arr) ==='[object Array]'

// true

Array.isArray(arr)

// true

语法:object instanceof constructor

参数:object(要检测的对象.)constructor(某个构造函数)

描述:instanceof 运算符用来检测constructor.prototype 是否存在于参数object 的原型链上。

instanceof 操作符是假定只有一种全局环境,如果网页中包含多个框架,多个全局环境,如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。(所以在这种情况下会不准确)

因为 constructor可以被重写,所以不能确保一定是数组。

conststr ='abc';

str.constructor =Array;

str.constructor ===Array

// true

你可能感兴趣的:(判断是否数组的方法)