findIndex -1
时间: 2023-10-10 16:07:56 浏览: 43
`findIndex` 方法用于找到数组中满足指定条件的元素的索引。如果没有找到符合条件的元素,则返回 -1。
例如,我们有一个数组 `[10, 20, 30, 40, 50]`,现在我们想要找到值为 30 的元素的索引,我们可以使用 `findIndex` 方法来实现:
```javascript
const arr = [10, 20, 30, 40, 50];
const index = arr.findIndex(element => element === 30);
console.log(index); // 输出 2
```
在这个例子中,`findIndex` 方法会遍历数组中的每个元素,当遇到值为 30 的元素时,返回该元素的索引值 2。
如果没有找到符合条件的元素,`findIndex` 方法将返回 -1。
相关问题
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。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)