gpt4 book ai didi

javascript - 理解 Array.isArray Polyfill

转载 作者:行者123 更新时间:2023-12-01 16:25:42 28 4
gpt4 key购买 nike

我正在浏览 polyfill MDN 上的 Array.isArray 方法,这是我发现的:

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

虽然这行得通,但我想知道为什么 MDN 没有将以下内容列为 isArray 的 polyfill?

if (!Array.isArray) {
Array.isArray = function(arg) {
return arg.constructor === Array;
};
}

上面的代码比较简短。我想知道与上面的实现相比,使用 MDN 的实现是否有任何优势?

最佳答案

使 MDN polyfill 成为安全使用的最重要原因是数组是一种奇异对象。区分奇异对象的最佳方法是通过使用与该对象相关的奇异特征 - 也就是说,奇异对象的奇异属性。

如果您查看 Object.prototype.toString 的规范方法,你会发现它使用了抽象操作isArray ,检查奇异数组对象。

另一方面,请查看 constructor property 的规范.它不是数组的奇异属性,因此 javascript 代码可以轻松更改它。

const x = [];
x.constructor = Object

事实上,constructor 属性更适合元编程。在 es5 中,您可以在不触及构造函数属性的情况下创建子类。

现在,以下是您的实现可能会出错的地方:

const customIsArray = function(arg) {
return arg.constructor === Array;
};

// 1) won't work with subclasses of Array

class CustomArray extends Array {
// ...
}

const customArray = new CustomArray()
customIsArray(customArray) // false
Array.isArray(customArray) // true

// 2) won't work across different realms (iframes, web workers, service workers ... if we are speaking about the browser environment)

const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
const IframeArray = iframe.contentWindow.Array;
const iframeArray = new IframeArray();
customIsArray(iframeArray) // false
Array.isArray(iframeArray) // true

// 3) won't work with few edge cases like (customIsArray will return true, while Array.isArray will return false)

const fakeArray1 = { __proto__: Array.prototype }
const fakeArray2 = { constructor: Array }

customIsArray(fakeArray1) // true
Array.isArray(fakeArray1) // false

customIsArray(fakeArray2) // true
Array.isArray(fakeArray2) // false

关于javascript - 理解 Array.isArray Polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62074163/

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