ZetCode

JavaScript find 方法

最后修改于 2025 年 4 月 4 日

在本文中,我们将展示如何使用 JavaScript 中的 find 方法搜索数组。

数组搜索

find 方法返回数组中满足提供的测试函数的第一个元素。如果没有任何值满足测试函数,则返回 undefined

当您需要根据特定条件在数组中查找特定元素时,此方法非常有用。find 方法不会修改原始数组,但会返回找到的元素或 undefined。

find 方法会为每个索引执行一次回调函数,直到找到回调返回真值的索引。它在找到第一个匹配元素后停止搜索。

基本的 find 示例

以下示例演示了 find 方法的基本用法。

main.js
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(element => element > 10);

console.log(found);

我们搜索第一个大于 10 的元素。find 方法返回 12,这是满足条件的第一个元素。原始数组保持不变。

$ node main.js
12

在数组中查找对象

find 方法特别适用于搜索对象数组。

main.js
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find(fruit => fruit.name === 'cherries');

console.log(result);

我们通过名称搜索对象数组中的特定水果。该方法返回名称与 'cherries' 匹配的整个对象。这演示了 find 如何处理复杂的数据结构。

$ node main.js
{ name: 'cherries', quantity: 5 }

使用带索引参数的 find

回调函数还可以访问当前元素的索引。

main.js
const numbers = [1, 5, 10, 15, 20];
const found = numbers.find((element, index) => {
  console.log(`Checking index ${index}: ${element}`);
  return element > 13;
});

console.log('Found:', found);

我们使用索引参数来记录每次搜索尝试。该方法在满足条件的第一个元素 (15) 处停止。这显示了 find 如何按顺序处理元素。

$ node main.js
Checking index 0: 1
Checking index 1: 5
Checking index 2: 10
Checking index 3: 15
Found: 15

带 thisArg 参数的 find

find 方法接受一个可选的 thisArg 参数,以设置回调函数中的 this 值。

main.js
function isPrime(element, index, array) {

  for (let i = 2; i < element; i++) {
    if (element % i === 0) return false;
  }
  
  return element > 1;
}

const numbers = [4, 6, 8, 9, 12, 13, 16];
const prime = numbers.find(isPrime);

console.log(prime);

我们定义了一个单独的函数来检查素数,并将其与 find 一起使用。该方法返回 13,这是数组中的第一个素数。这演示了使用命名函数而不是箭头函数。

$ node main.js
13

当未找到任何元素时

当未找到匹配项时,find 方法返回 undefined

main.js
const numbers = [1, 3, 5, 7, 9];
const even = numbers.find(num => num % 2 === 0);

console.log(even);
console.log(typeof even);

我们在一个奇数数组中搜索一个偶数。由于没有任何元素满足条件,find 返回 undefined。此行为对于代码中的错误处理非常重要。

$ node main.js
undefined
undefined

来源

数组 find - 语言参考

在本文中,我们已经演示了如何使用 find() 方法在 JavaScript 中搜索数组。

作者

我的名字是 Jan Bodnar,我是一个充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 JS 数组函数。