gpt4 book ai didi

javascript - 有人可以解释这个 Array.prototype.find() polyfill 吗?

转载 作者:数据小太阳 更新时间:2023-10-29 04:09:05 26 4
gpt4 key购买 nike

在此 MDN 页面上 [ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find]有这个 polyfill:

if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
configurable: true,
writable: true,
value: function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;

for (var i = 0; i < length; i++) {
if (i in list) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
}
return undefined;
}
});
}

我的问题是这些行是做什么用的:

var list = Object(this);
var length = list.length >>> 0;

因为 this 肯定是一个数组(我们正在扩充 Array.prototype)所以为什么要确保 length 是数字,为什么要使用 Object()?

最佳答案

基本的答案是 polyfill 只是忠实地实现了 ES6 规范草案(截至 5 月 22 日草案的第 22.1.3.8 节)中算法的第 1 步和第 4 步。

1. Let O be the result of calling ToObject passing the this value as the argument.

...

4. Let len be ToLength(lenValue).

(其中 ToLength 基本上是对数字的转换。)

而且现在可以为 this 使用非对象值(通过 Function#callFunction#apply,或者仅通过在严格模式下直接调用函数),步骤 1 有意义。

since this is definitely an array (we are augmenting Array.prototype) so why make sure length is numerical, and why is Object() used?

但是我们不知道 this 是一个数组。请参阅当前 ES6 规范草案中的注释:

The find function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the find function can be applied successfully to an exotic object that is not an Array is implementation-dependent.

您会在分配给原型(prototype)的几乎所有预定义函数上找到该注释。

例如,您可以将它们用于其他用途,方法是将它们直接分配给对象或其他原型(prototype):

MyNiftyThing.prototype.find = Array.prototype.find;

...或通过 Function#callFunction#apply .

假设我想在一个arguments 对象上使用Array#findarguments 当然是类数组 但不是数组。所以我可能会这样做:

function foo() {
var firstObject = Array.prototype.find.call(arguments, function(val) {
return typeof val === "object";
});
// ...
}

一个更著名的例子(不涉及find)是使用slice将类数组对象转换为数组:

function foo() {
// Turn the `arguments` pseudo-array into a real array
var args = Array.prototype.slice.call(arguments, 0);
}

关于javascript - 有人可以解释这个 Array.prototype.find() polyfill 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24183104/

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