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

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

问题描述

有两种方法可以判断数组是数组还是对象.使用 typeof item === "object"; 将为对象和数组返回 true,因为数组对于 javascript 来说相对较新,而数组是对象的原型(可能措辞有误,请随时更正我).所以我知道的两种确定数组是否为数组的方法是:

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:

解决方案 1:

Array.isArray(item);

解决方案 2:

item instanceof Array;

我的问题是:

  1. 这两种解决方案有什么区别?
  2. 这两种解决方案中哪个是首选解决方案?
  3. 哪个处理时间更快?

推荐答案

1.这两种方案有什么区别?

1.What is the difference between these two solutions?

isArray 是旧浏览器不支持的 ES5 方法,但它可以可靠地确定对象是否为数组.

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

instanceof检查 Array.prototype 是否在对象的 [[Prototype]] 链上.它在跨帧检查数组时失败,因为用于实例的 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.这两个中哪个是首选解决方案?

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]')

适合 ES3 浏览器并跨框架工作.如果只考虑 ES5 浏览器,isArray 可能没问题.

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

3.哪个处理时间更快?

3.Which has a faster process time?

基本上不相关,因为两者的处理时间都可以忽略不计.更重要的是选择一个可靠的.可以将 Array.isArray 方法添加到没有内置它的浏览器中:

Largely irrelevant, since the processing time for both is negligible. 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 Array 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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