普通函数写findIndex
时间: 2024-01-05 17:43:00 浏览: 38
以下是一个普通函数 `findIndex` 的实现:
```javascript
function findIndex(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
return i;
}
}
return -1;
}
```
该函数接受一个数组和一个回调函数作为参数。它遍历数组中的每个元素,并对每个元素调用回调函数。如果回调函数返回 `true`,则返回当前元素的索引。如果没有找到匹配项,则返回 `-1`。
示例用法:
```javascript
const arr = [1, 2, 3, 4, 5];
const index = findIndex(arr, (item) => item === 3);
console.log(index); // 输出 2
```
相关问题
js findIndex()函数
findIndex()函数是JavaScript中的一个数组方法,用于查找满足指定条件的第一个元素的索引值。该方法不会改变原始数组的值。它接受一个回调函数作为参数,该回调函数用于定义查找的条件。如果找到符合条件的元素,则返回该元素的索引值;如果没有找到,则返回-1。
下面是findIndex()函数的使用示例:
```
const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5];
// 使用箭头函数作为回调函数
const index = arr.findIndex(item => item > 2);
console.log(index); // 输出2
// 使用普通函数作为回调函数
const index = arr.findIndex(function(item) {
return item > 2;
});
console.log(index); // 输出2
```
在上述示例中,我们创建了一个数组`arr`,然后使用`findIndex()`方法查找第一个大于2的元素的索引值,并将结果存储在变量`index`中。最后,我们通过`console.log()`函数将结果打印出来。输出结果都是2,因为数组中第一个大于2的元素是3,对应的索引值为2。
需要注意的是,如果数组中没有符合条件的元素,`findIndex()`方法将返回-1。此外,ES6还为数组提供了`find()`方法,用于查找目标元素本身,而不是返回索引值。
findIndex()
findIndex() 是一个数组方法,用于在数组中查找满足某个条件的元素,并返回其索引值。它接受一个回调函数作为参数,该回调函数用于定义查找的条件。
使用示例:
```javascript
const array = [10, 20, 30, 40, 50];
// 使用箭头函数作为回调函数
const index = array.findIndex(element => element > 30);
console.log(index); // 输出:3
// 使用普通函数作为回调函数
function isEven(element) {
return element % 2 === 0;
}
const index2 = array.findIndex(isEven);
console.log(index2); // 输出:1
```
在上面的示例中,`findIndex()` 方法通过回调函数查找数组 `array` 中第一个大于 30 的元素,返回其索引值 3。另外一个示例中,通过回调函数 `isEven` 查找数组中第一个满足偶数条件的元素,返回其索引值 1。
需要注意的是,如果数组中没有满足条件的元素,`findIndex()` 方法将返回 -1。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)