使用Array.isArray和阵列的instanceof的区别 [英] Difference between using Array.isArray and instanceof Array

查看:1512
本文介绍了使用Array.isArray和阵列的instanceof的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以计算出,如果一个数组是一个数组或对象。使用的typeof项目===对象; 因为数组是比较新的JavaScript和数组是对象的原型将返回true的对象和数组(可能这个措辞错了,请随时指正)。因此,两种方式我知道,以确定是否数组是一个阵列:

解决方案1:

  Array.isArray(项目);

解决方案2:

 的instanceof阵列项目;

我的问题是:


  1. 什么是这两种解决方案之间的区别?

  2. 这两个就是preferred解决方案?

  3. 其中有一个更快的处理时间?


解决方案

  

1.什么是这两种解决方案之间的区别?


IsArray的是一个ES5方法,以便不由旧的浏览器的支持,但它可靠地确定某个对象是一个Array。

的instanceof 如果只检查的 Array.prototype 的是一个对象的 [[原型]] 链。跨框架检查数组时失败,因为的阵列的使用实例构造函数将可能是用于测试的不同。


  

这两个2.Which是preferred解决方案?


preferred承担一定的选择标准。一般来说,preferred的方法是这样的:

 如果(Object.prototype.toString.call(OBJ)=='[对象数组]')

这适合ES3的浏览器和跨框架工程。如果只ES5的浏览器都在考虑的 IsArray的的有可能确定。


  

3.Which拥有更快的处理时间?


基本上是无能为力的,因为处理时间都为微不足道。更为重要的是要选择的一个是可靠的。一个的 Array.isArray 的方法可以添加到没有它内置的浏览器中使用:

 如果(!Array.isArray){
    Array.isArray =功能(OBJ){
      返回Object.prototype.toString.call(OBJ)=='[对象数组]';
    }
}

There is two ways to figure out if an array is an array or an object. Using typeof item === "object"; will return true for an object and an array since arrays are relatively new to javascript and arrays are prototypes of objects(may have worded this wrong, feel free to correct me). So the two ways I know of to determine if an Array is an Array are:

Solution 1:

Array.isArray(item);

Solution 2:

item instanceof Array;

My questions are:

  1. What is the difference between these two solutions?
  2. Which of these two is the preferred solution?
  3. Which has a faster process time?

解决方案

1.What is the difference between these two solutions?

isArray is an ES5 method so not supported by older browsers, but it reliably determines if an object is an Array.

instanceof only checks if Array.prototype is on an object's [[Prototype]] chain. It fails when checking arrays across frames since the Array constructor used for the instance will likely be different to the one used for the test.

2.Which of these two is the preferred solution?

"Preferred" assumes some criterion for selection. Generally, the preferred method is something like:

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

which suits ES3 browsers and works across frames. If only ES5 browsers are in consideration, isArray is likely OK.

3.Which has a faster process time?

Largely irrelevant, since the processing time for both is negligable. Far more important to select the one that is reliable. An Array.isArray method can be added to browsers that don't have it built–in using:

if (!Array.isArray) {
    Array.isArray = function(obj) {
      return Object.prototype.toString.call(obj) == '[object Array]';
    }
}

这篇关于使用Array.isArray和阵列的instanceof的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆