JavaScript Array.find()教程 - 如何遍历数组中的元素

87 阅读5分钟

当你处理一个数组集合时,有时你只需要找出数组中是否存在一个项目,以便你可以检索它。而你并不关心在同一个数组中还有多少项(如果有的话)存在。

那么,我们可以使用find() 方法来做这件事。

Array.find()方法如何工作

find() 方法是一个Array.prototype (又称内置)方法,它接收一个回调函数,并为它所绑定的数组内的每个项目调用该函数。

当它找到一个匹配项时(换句话说,回调函数返回true ),该方法返回那个特定的数组项,并立即中断循环。因此,find() 方法返回数组内满足回调函数的第一个元素。

回调函数可以接受以下参数:

  • currentItem:这是当前被迭代的数组中的元素。
  • index:这是currentItem 在数组中的索引位置。
  • array:代表目标数组及其所有项目。

如何在JavaScript中使用find() 方法

在下面的例子中,我将演示如何使用find() 方法从一个数组中获取符合指定条件的第一个项目,在JavaScript中。

如何用find()方法获取一个单项

让我们假设你有一只狗失踪了。你向有关部门报告,他们召集了一批找回的狗。

为了能够找到你的狗,你需要提供关于它的独特信息。例如,你的狗的品种(吉娃娃)可能被用来识别它。

我们可以在JavaScript中使用数组集合来表达这种情况。被称为foundDogs 的数组将包含所有回收的狗的名字以及它们各自的品种。而我们将使用find() 方法,从数组里面找到属于吉娃娃的狗:

let foundDogs = [{
    breed: "Beagle",
    color: "white"
  },

  {
    breed: "Chihuahua",
    color: "yellow"
  },

  {
    breed: "Pug",
    color: "black"
  },
]

function findMyDog(dog) {
  return dog.breed === "Chihuahua"
}

let myDog = foundDogs.find(dog => findMyDog(dog));

console.log(myDog);


/*

{
  breed: "Chihuahua",
  color: "yellow"
}

*/

当找到一个匹配的名字时,查找方法就会停止迭代。

关于find() ,有一些非常重要的东西需要记住:一旦回调函数返回一个true 语句,它就停止执行。

为了说明这一点,我们将再次使用失踪的狗的例子。这一次,我们将假设找到了两只吉娃娃。

但是find() 方法将只返回它在数组中发现的第一个吉娃娃的实例。任何其他实例随后都会被忽略。

我们也可以通过将该项目的索引位置记录到控制台来轻松地看到这一点:

let foundDogs = [{
    breed: "Beagle",
    color: "white"
  },

  {
    breed: "Chihuahua",
    color: "yellow"
  },

  {
    breed: "Pug",
    color: "black"
  },
  
  {
    breed: "Chihuahua",
    color: "yellow"
  }
]


function findMyDog(dog, index) {
	if (dog.breed === "Chihuahua") console.log(index);
  return dog.breed === "Chihuahua"
}


let myDog = foundDogs.find((dog, index) => findMyDog(dog, index));


console.log(myDog);

/* 
1

{
  breed: "Chihuahua",
  color: "yellow"
}

*/

返回索引为1的第一个实例

如何使用结构化赋值

你可以通过结合结构化赋值和箭头函数表达式使你的代码更加简洁。

我们将使用结构化赋值从对象中只提取名称属性,然后作为参数传递给回调函数。

我们会得到同样的结果:

let foundDogs = [{
    breed: "Beagle",
    color: "white"
  },

  {
    breed: "Chihuahua",
    color: "yellow"
  },

  {
    breed: "Pug",
    color: "black"
  },
]

 


let myDog = foundDogs.find(({breed}) => breed === "Chihuahua");

console.log(myDog);

/*

{
  breed: "Chihuahua",
  color: "yellow"
}

*/

如何通过索引找到一个项目

在这个例子中,我们将使用唯一的索引值从数组中找到并返回属于'David'的点。这展示了我们可以在我们的callback 函数中使用find() 方法中的index 属性的一种方式:

let reservedPositions = [{
    name: "Anna",
    age: 24
  },

  {
    name: "Beth",
    age: 22
  },

  {
    name: "Cara",
    age: 25
  },
  
  {
    name: "David",
    age: 30
  },
  
  {
    name: "Ethan",
    age: 26
  }
]


function findByIndex(person, index) {
  return index === 3
}


let myPosition = reservedPositions.find((person, index) => findByIndex(person, index));

console.log(myPosition);

/*
{
  age: 30,
  name: "David"
}
*/

你可以用find()来使用上下文对象

除了回调函数之外,find() 方法还可以接收一个上下文对象:

find(callback, contextObj)

然后我们可以在每次迭代时从回调函数内部引用这个对象,使用this 关键字作为引用。这使得我们可以访问定义在上下文对象中的任何属性或方法。

如何使用find()的上下文对象

假设我们有一个工作申请的数组,想只选择第一个符合所有标准的申请人。

所有的标准被定义在一个叫做criteria 的上下文对象里面,这个对象随后被作为第二个参数传入find() 方法。然后,在回调函数中,我们访问该对象,以检查一个申请人是否符合其中指定的所有标准:

let applicants = [
    {name: "aaron", yrsOfExperience: 18, age: 66},
    {name: "beth", yrsOfExperience:  0, age: 18},
    {name: "cara", yrsOfExperience: 4, age: 22},
    {name: "daniel", yrsOfExperience: 3, age: 16},
    {name: "ella", yrsOfExperience: 5, age: 25},
    {name: "fin", yrsOfExperience: 0, age: 16},
    {name: "george", yrsOfExperience: 6, age: 28},
]

let criteria = {
	minimumExperience: 3,
  lowerAge: 18,
  upperAge: 65
}

   
let luckyApplicant = applicants.find(function(applicant) {
	return applicant.yrsOfExperience >= this.minimumExperience && applicant.age <= this.upperAge
  && applicant.age >= this.lowerAge ;
}, criteria)

console.log(luckyApplicant);

/*
{
  age: 22,
  name: "cara",
  yrsOfExperience: 4
}
*/

从技术上讲,三个申请人(Cara、Ella和George)根据标准都符合资格。换句话说,他们三人至少18岁,不超过65岁,并且至少有3年的工作经验。

然而,由于find() 方法总是只返回第一个评估为 "真 "的实例,其他两个实例将被忽略,循环将被打破。

总结

find() 方法是一个Array.prototype 方法,它接收了一个回调函数,并为绑定数组中的每个项目调用该函数。

当回调函数的值为true ,该方法返回当前的项目并中断循环。它只返回第一个匹配项--数组内的任何其他匹配项将被忽略。

除了回调函数之外,find() 方法还可以接收一个上下文对象作为第二个参数。这将使你能够使用this ,从回调函数中访问其任何属性。

谢谢你的阅读,再见。