gpt4 book ai didi

javascript - 使用 Array.isArray 和 instanceof Array 的区别

转载 作者:IT王子 更新时间:2023-10-29 03:01:04 49 4
gpt4 key购买 nike

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

解决方案一:

Array.isArray(item);

解决方案 2:

item instanceof Array;

我的问题是:

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

最佳答案

1.What is the difference between these two solutions?

isArray是一种 ES5 方法,因此不受旧版浏览器支持,但它可以可靠地确定对象是否为数组。

instanceof只检查 Array.prototype 是否在对象的 [[Prototype]] 链上。它在跨帧检查数组时失败,因为用于实例的 Array 构造函数可能与用于测试的构造函数不同。

2.Which of these two is the preferred solution?

“首选”假定了一些选择标准。通常,首选方法类似于:

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

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

3.Which has a faster process time?

在很大程度上无关紧要,因为两者的处理时间可以忽略不计。选择可靠的产品更为重要。可以将 Array.isArray 方法添加到没有内置它的浏览器中,使用:

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

关于javascript - 使用 Array.isArray 和 instanceof Array 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22289727/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com