Array.prototype.find()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.

Array 实例的 find() 方法返回所提供数组中满足所提供测试函数的第一个元素。如果没有值满足测试函数,则返回 undefined

¥The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

  • 如果需要数组中找到的元素的索引,请使用 findIndex()
  • 如果需要查找某个值的索引,请使用 indexOf()。(它与 findIndex() 类似,但检查每个元素是否与值相等,而不是使用测试函数。)
  • 如果需要查找数组中是否存在某个值,请使用 includes()。同样,它检查每个元素是否与值相等,而不是使用测试函数。
  • 如果需要查找某个元素是否满足所提供的测试功能,请使用 some()
  • 如果需要查找满足所提供的测试功能的所有元素,请使用 filter()

Try it

语法

¥Syntax

js
find(callbackFn)
find(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对数组中的每个元素执行的函数。它应该返回 truthy 值以指示已找到匹配元素,否则返回 falsy 值。使用以下参数调用该函数:

element

数组中当前正在处理的元素。

index

数组中当前正在处理的元素的索引。

array

调用了数组 find()

thisArg Optional

执行 callbackFn 时用作 this 的值。参见 迭代法

返回值

¥Return value

数组中满足所提供的测试函数的第一个元素。否则,返回 undefined

¥The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

描述

¥Description

find() 方法是 迭代法 方法。它按升序索引顺序为数组中的每个元素调用一次提供的 callbackFn 函数,直到 callbackFn 返回 truthy 值。然后 find() 返回该元素并停止遍历数组。如果 callbackFn 从未返回真值,则 find() 返回 undefined。请阅读 迭代法 部分,了解有关这些方法一般如何工作的更多信息。

¥The find() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. find() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, find() returns undefined. Read the iterative methods section for more information about how these methods work in general.

callbackFn 会针对数组的每个索引调用,而不仅仅是那些已分配值的索引。稀疏数组 中的空插槽的行为与 undefined 相同。

¥callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined.

find() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The find() method is generic. It only expects the this value to have a length property and integer-keyed properties.

示例

¥Examples

通过其属性之一查找数组中的对象

¥Find an object in an array by one of its properties

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

function isCherries(fruit) {
  return fruit.name === "cherries";
}

console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }

使用箭头函数和解构

¥Using arrow function and destructuring

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

const result = inventory.find(({ name }) => name === "cherries");

console.log(result); // { name: 'cherries', quantity: 5 }

查找数组中的质数

¥Find a prime number in an array

以下示例在数组中查找素数元素(如果不存在素数则返回 undefined):

¥The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):

js
function isPrime(element, index, array) {
  let start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

使用 callbackFn 的第三个参数

¥Using the third argument of callbackFn

如果你想访问数组中的另一个元素,特别是当你没有引用该数组的现有变量时,array 参数非常有用。以下示例首先使用 filter() 提取正值,然后使用 find() 查找第一个小于其邻居的元素。

¥The array argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter() to extract the positive values and then uses find() to find the first element that is less than its neighbors.

js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
  .filter((num) => num > 0)
  .find((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(firstTrough); // 1

在稀疏数组上使用 find()

¥Using find() on sparse arrays

访问稀疏数组中的空槽,并按与 undefined 相同的方式处理。

¥Empty slots in sparse arrays are visited, and are treated the same as undefined.

js
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];

// Shows all indexes, not just those with assigned values
array.find((value, index) => {
  console.log("Visited index", index, "with value", value);
});
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value 5
// Visited index 6 with value 6

// Shows all indexes, including deleted
array.find((value, index) => {
  // Delete element 5 on first iteration
  if (index === 0) {
    console.log("Deleting array[5] with value", array[5]);
    delete array[5];
  }
  // Element 5 is still visited even though deleted
  console.log("Visited index", index, "with value", value);
});
// Deleting array[5] with value 5
// Visited index 0 with value 0
// Visited index 1 with value 1
// Visited index 2 with value undefined
// Visited index 3 with value undefined
// Visited index 4 with value undefined
// Visited index 5 with value undefined
// Visited index 6 with value 6

对非数组对象调用 find()

¥Calling find() on non-array objects

find() 方法读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

¥The find() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

js
const arrayLike = {
  length: 3,
  "-1": 0.1, // ignored by find() since -1 < 0
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)));
// 7.3

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.find

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看