JavaScript array method find(), detailed use (js find() method)

Introduction:find() The method is used in JavaScript to find the first element of a specific condition in the array. If an element is found so that the callback function returns true, the element is returned as the result; if no such element is found, undefined is returned. The function The original array is not modified.

1.  Basic grammar

array.find((item,index)=>{
  console.log(item,index);
})

array.find(callback(element[, index[, array]])[, thisArg])

Parameter explanation:

  • callback: Required. The function to be performed on each element in the array.
  • element: Required. The array element currently being processed.
  • index: Optional. The index of the element being processed.
  • array: Optional. The array itself that called the method.
  • thisArg: Optional. The value to use when executing the callback function  this .

2.  Callback function

find()The first parameter of the method callbackis a function to test whether each element meets the conditions, receiving three

parameter:

  • element: Indicates the element currently being processed.
  • index: Indicates the index of the element being processed.
  • array: Indicates the array object currently being processed.

The callback function should return a boolean indicating whether the current element meets our criteria. If it returns true, it stops traversing and returns the value of the element; otherwise, it continues traversing until it encounters a qualified element or the entire array is traversed.

3.  Example of use

find()The practical application of the method:

Example 1: Find the first negative number in the array.

const arr = [1, 2, -3, 4, -5]; 
const negativeNum = arr.find(num => num < 0); 
console.log(negativeNum); // 输出:-3

Example 2: Find the eligible objects from the object array.

const users = [ 
 {id: 1, name: 'Alice'},
 {id: 2, name: 'Bob'},
 {id: 3, name: 'Charlie'}
]; 
const user = users.find(u => u.id === 2);
console.log(user); // 输出:{id: 2, name: 'Bob'}

Example 3: Use thisArgthe parameter to specify the value in the callback function this.

function isEven(num) { return num % 2 === 0; } 
const nums = [1, 3, 4, 7, 8]; 
const evenNum = nums.find(isEven, this); 
console.log(evenNum); // 输出:4

★Precautions

  1. find() The method traverses the entire array until an element that meets the condition is found or the entire array is traversed.
  2. Returns if the array is empty  undefined.
  3. It is not a good practice to modify the array itself in the callback function. If you want to modify the array, use  the map() or  filter() method.
  4. When multiple elements meet the condition, find() the method will only return the first one that meets the condition.
  5. find() Methods are new in ES6 and may not be supported in older browsers.

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/130502800