1. 使用 Array.isArray() 方法,推荐

let arr = [1,2,3,4]
console.log(Array.isArray(arr)) // true

 

2. 使用 Object.prototype.toString.call() 方法,该方法不仅能判断数组,还能判断 function('[object Function]')、number('[object Number]') 等数据

let arr = [1,2,3,4]
console.log(Object.prototype.toString.call(arr) == '[object Array]') // true

 

3. 通过 instanceof、constructor 方法去判断,有一定的风险,不推荐

正常情况下

let a = [1,3,4];
a.constructor === Array; //true
// 或者
let a = [1,3,4];
a instanceof Array; //true

但是需要注意的是,prototype属性是可以修改的,所以并不是最初判断为true就一定永远为真。其次,当我们的脚本拥有多个全局环境,例如html中拥有多个iframe对象,instanceof的验证结果可能不会符合预期,例如:

//为body创建并添加一个iframe对象
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
//取得iframe对象的构造数组方法

xArray = window.frames[0].Array;
//通过构造函数获取一个实例
var arr = new xArray(1, 2, 3);
arr instanceof Array; //false

// 或者
    
xArray = window.frames[window.frames.length-1].Array;
//通过构造函数获取一个实例
var arr = new xArray(1,2,3); 
arr.constructor === Array; //false

导致这种问题是因为iframe会产生新的全局环境,它也会拥有自己的Array.prototype属性,让不同环境下的属性相同很明显是不安全的做法,所以Array.prototype !== window.frames[0].Array.prototype,想要arr instanceof Array为true,你得保证arr是由原始Array构造函数创建时才可行。