判断数组的方式有哪些?如何区分一个数组是数组还是对象?如何区分一个数据类型是数组还是对象?

103 阅读2分钟

1、Object.prototype.toString.call(),返回“[object Xxx]”的字符串(推荐)

Object.prototype.toString.call(obj);

2、Array.isArray()

Array.isArray() ES5 新增的,IE8+ 才兼容。

Array.isArrray(obj);   //返回布尔值

3、通过 instanceof 做判断

obj instanceof Array;   //返回布尔值

4、通过 constructor 做判断

obj.constructor === Array;   //返回布尔值

注意:如果创建一个对象来改变它的原型,constructor就不能用来判断数据类型了:即使是 ture 也不一定是数组。

function SubArray(){}
SubArray.prototype = [];
var myArray = new SubArray;
console.log(myArray.constructor === Array); // true

5、通过原型链做判断

obj.__proto__ === Array.prototype;   //返回布尔值

6、Array.prototype.isPrototypeOf

Array.prototype.isPrototypeOf(obj);   //返回布尔值

7、Object.getPrototypeOf()

Object.getPrototypeOf() ⽅法返回指定对象的原型

Object.getPrototypeOf(obj) === Array.prototype;   //返回布尔值

注意!但是方法 3、4、5、6 和 7 会有⼀个问题,它们的问题在于需要假定只有⼀个全局执⾏的环境。如果⽹页中包含多个框架,那实际上就存在两个及以上不同的全局执⾏环境,从⽽存在两个以上不同版本的 Array 构造函数。如果你从第⼀个框架向第二个框架传⼊⼀个数组,那么传⼊的数组与在第二个框架中原⽣创建的数组分别具有不同的构造函数。所以导致它的原型和第二个框架中的原生数组的原型不一样。

var a = [];
console.log(a instanceof Array);  // true
console.log(a.constructor === Array);  // true
console.log(a.__proto__ === Array.prototype);  // true
console.log(Array.prototype.isPrototypeOf(a));  // true
console.log(Object.getPrototypeOf(a) === Array.prototype);  // true
console.log(Array.isArray(a)); // true
console.log(Object.prototype.toString.call(a)); // [object Array]

var frame = document.createElement("iframe"); // 创建一个框架
document.body.appendChild(frame); // 往body标签里面的末尾加入新创建的框架
console.log(window.frames);
console.log(window.frames[0]);
console.log(window.frames[0].Array); // ƒ Array() { [native code] }
var c = window.frames[0].Array; // 取得新创建框架全局执行环境中的Array构造函数
var d = new c(); // 在新框架全局执行环境中创建一个数组d
console.log(d instanceof Array); // 在当前页面的执行环境中用 instanceof 操作符判断d是否为数组,返回false
console.log(d.constructor === Array);  // false
console.log(d.__proto__ === Array.prototype);  // false
console.log(Array.prototype.isPrototypeOf(d));  // false
console.log(Object.getPrototypeOf(d) === Array.prototype);  // false
console.log(Array.isArray(d)); // true
console.log(Object.prototype.toString.call(d)); // [object Array]

综上:

  1. 判断是否为数组:可以使用 Object.prototype.toString.call() 和 Array.isArray() 方法
  2. 判断是否为对象:使用Object.prototype.toString.call()方法