1.JavaScript 的 find()
方法
用于查找数组中符合条件的第一个元素,并返回该元素。这个方法接受一个回调函数作为参数,回调函数会对数组中的每个元素进行执行,直到找到满足条件的元素为止。
find()
方法的基本语法:
| array.find(function(currentValue, index, arr), thisValue) |
复制
function(currentValue, index, arr)
: 用于定义对数组元素的检测条件的回调函数。它可以接受三个参数:
currentValue
: 当前正在处理的数组元素。index
(可选): 当前正在处理的数组元素的索引。arr
(可选): 调用了 find()
方法的数组。
thisValue
(可选): 在执行回调函数时,用作 this
的值
2.使用 find()
方法查找数组中符合条件的第一个元素
| const numbers = [10, 20, 30, 40, 50]; |
| |
| |
| const result = numbers.find(function(element) { |
| return element > 25; |
| }); |
| |
| console.log(result); |
复制
3.使用箭头函数简化回调函数
| const numbers = [10, 20, 30, 40, 50]; |
| |
| |
| const result = numbers.find(element => element > 25); |
| |
| console.log(result); |
复制
4.查找字符串数组中包含指定字符的第一个元素
| const fruits = ['apple', 'banana', 'cherry', 'date']; |
| |
| |
| const result = fruits.find(fruit => fruit.includes('a')); |
| |
| console.log(result); |
复制