gpt4 book ai didi

javascript - 这个 Array.prototype.find() 是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 14:05:11 25 4
gpt4 key购买 nike

我不明白的是该函数及其参数fruit,因为它没有传递任何内容。

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries));

最佳答案

...because it's not being passed anything.

正在传递一些东西,你只是看不到执行此操作的代码,它位于Array.prototype.find内部方法的代码。请记住,这一行:

console.log(inventory.find(findCherries));

...将 findCherries(函数引用)的传递给find,它不调用 findCherriesfind 会为数组中的每个条目执行一次,并提供三个参数(findCherries 仅使用其中一个参数)。第一个参数是该调用的数组条目。

Array.prototype.find 的完整 polyfill 会使阅读变得棘手,所以让我们做一些类似但更简单的事情,以便您可以看到调用:

// A bit like Array.prototype.find, but **not** the same; much simplified
function fakeFind(callback) {
for (var index = 0; index < this.length; ++index) {
var entry = this[index];
// vvvvvvvvvvvvvvvvvvvvvvvvvvvv---- This is where findCherries is called
if (callback(entry, index, this)) {
return entry;
}
}
return undefined;
}

实时复制:

// A bit like Array.prototype.find, but **not** the same; much simplified
function fakeFind(callback) {
for (var index = 0; index < this.length; ++index) {
var entry = this[index];
// vvvvvvvvvvvvvvvvvvvvvvvvvvvv---- This is where findCherries is called
if (callback(entry, index, this)) {
return entry;
}
}
return undefined;
}
Object.defineProperty(Array.prototype, "fakeFind", {
value: fakeFind
});
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
return fruit.name === 'cherries';
}

console.log(inventory.fakeFind(findCherries));

关于javascript - 这个 Array.prototype.find() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40105038/

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