簡體   English   中英

"這個 Array.prototype.find() 是如何工作的?"

[英]How does this Array.prototype.find() work?

我不明白的是函數及其參數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));

...因為它沒有被傳遞任何東西。

傳遞的東西,你只是看不到代碼這樣做,這是內部 Array.prototype.find方法的代碼。 記住,這一行:

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

...將findCherries (函數引用)的傳遞給find ,它不調用 findCherries find會為數組中的每個條目一次提供三個參數( findCherries僅使用其中一個)。 這些參數中的第一個是該調用的數組條目。

Array.prototype.find的完整Array.prototype.find使得Array.prototype.find棘手,所以讓我們做一些類似但更簡單的事情,以便您看到調用:

// 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)); 

如果擴展該函數以使其使用匿名函數,則這更有意義。

如果您查看下面的代碼段,它會稍微說明一下。

 var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function findCherries(fruit) { return fruit.name === 'cherries'; } //this kind of does the same, apart from the extra anonymous function //but here you can see this `item` that's getting passed console.log(inventory.find( function (item) { return findCherries(item); } )); //because in the above the anonymous function has the same //signature, it's made redunant, so we may as well //call findCherries direct.. console.log(inventory.find(findCherries)); 

如果數組中的元素滿足提供的測試功能,則find()方法將在數組中返回一個值。 否則返回undefined。 Array.prototype.find()

在您的代碼段中, fruit是原始數組中的一項,即它的值是數組中的一項。 findCherries將比較數組中的每個元素是否與屬性name匹配(這是提供的測試功能)。

您的findCherries回調將在數組中的每個值上執行。 找到匹配項后,將返回結果。

數組查找方法的實現。

 Array.prototype.MyFind = function(callback) { for (let i = 0; i < this.length; i++) { if(callback(this[i])){ return this[i]; } } } const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10 & element > 30 & element < 50); console.log(found);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM