findIndex跟find
时间: 2024-01-05 10:17:55 浏览: 30
findIndex和find都是ES6为Array增加的函数,它们都用于查找目标元素,但是返回值不同。find()函数用来查找目标元素(查找符合条件的第一个元素),找到就返回该元素,找不到返回undefined,而findIndex()函数也是查找目标元素(查找符合条件的第一个元素),找到就返回元素的位置,找不到就返回-1。相比之下,findIndex()更适合用于查找数组中某一项的索引,而find()则更适合用于查找数组中某一项的值。因此,在使用时需要根据具体的需求来选择使用哪个函数。
举个例子,如果我们要查找数组中第一个大于10的元素的索引,可以使用findIndex()函数,代码如下:
```
const arr = [5, 8, 12, 15, 20];
const index = arr.findIndex(item => item > 10);
console.log(index); // 2
```
而如果我们要查找数组中第一个大于10的元素的值,可以使用find()函数,代码如下:
```
const arr = [5, 8, 12, 15, 20];
const value = arr.find(item => item > 10);
console.log(value); // 12
```
相关问题
findIndex
`findIndex` 是 JavaScript 中的一个数组方法,用于查找符合条件的元素在数组中的索引位置。该方法接收一个回调函数作为参数,该回调函数接收三个参数:当前元素值、当前元素索引和被操作的数组,如果回调函数返回 `true`,则 `findIndex` 方法返回该元素在数组中的索引位置;如果回调函数对所有元素都返回 `false`,则 `findIndex` 返回 `-1`。
例如,下面的代码演示了如何使用 `findIndex` 方法查找数组中第一个值为 3 的元素的索引位置:
```javascript
const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex(num => num === 3);
console.log(index); // 输出 2
```
在上面的代码中,回调函数接收当前元素值 `num`,如果 `num` 等于 3,则返回 `true`,否则返回 `false`。由于数组中第三个元素的值是 3,因此 `findIndex` 方法返回 2,即该元素在数组中的索引位置。
JS findIndex
JS的findIndex方法用于查找数组中满足条件的第一个元素的下标。下面是两种使用findIndex方法的例子:
1. 使用箭头函数:
```javascript
const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5];
const index = arr.findIndex(item => item > 2);
console.log(index); // 输出:2
```
2. 直接使用条件表达式:
```javascript
const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5];
const index = arr.findIndex(item => item > 2);
console.log(index); // 输出2
```
注意:findIndex方法返回的是满足条件的第一个元素的下标。如果没有满足条件的元素,则返回-1。