JavaScript数组方法之findIndex()的用法详解

 更新时间:2023年10月11日 16:59:06   作者:史上最菜开发  
findIndex()方法是一个非常实用的数组方法,可以帮助我们快速查找符合某个条件的元素,本文给大家介绍JavaScript数组方法之findIndex()的用法,感谢的朋友跟随小编一起看看吧

findIndex()的用法

定义和用法:

findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

有两点要注意:

1. 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。例子2就是一个很好的说明,即使后面的666和66大于50,但是它只找到99,就不会执行后面的循环了。
2.如果没有符合条件的元素返回 -1

例子1:

var arr = ['a','b','c','d'];
? ?var flag = arr.findIndex(item => {
? ? ? ? return item === 'c';
? ? })
? ? console.log(flag) // 得到: 2

例子2:

var arr2 = [1,18,2,99,666,44,66];
? ? var flag2 = arr2.findIndex(item => {
? ? ? ? return item > 50;
? ? });
? ? console.log(flag2) ? // 得到: 3

例子3:

var arr3 = ['red','pink','green'];
? ? var flag3 = arr3.findIndex(item => item === 'yellow')
? ? console.log(flag3) ?// 得到:-1

注意: IE 11 及更早版本不支持 findIndex() 方法。

JavaScript数组方法之findIndex()详解

一、什么是findIndex()方法

在JavaScript中,如果我们需要在数组中查找满足某个条件的元素,就可以使用数组方法findIndex()。这个方法会依次遍历数组中的元素,找到第一个满足条件的元素,然后返回该元素的索引值。如果没有满足条件的元素,findIndex()就会返回-1。

const array1 = [5, 12, 8, 130, 44];
  const result = array1.findIndex(element => element > 10);
  console.log(result); // Output: 1

二、findIndex()方法如何使用

使用findIndex()方法需要传入一个回调函数,这个回调函数接受三个参数:数组元素、元素索引和数组本身。回调函数中可以编写我们需要的条件,如果某个元素符合条件,findIndex()就会返回该元素的索引值。

需要注意的是,findIndex()只会返回第一个符合条件的元素的索引值,不会继续往下找。

const array1 = [5, 12, 8, 130, 44];
  const result = array1.findIndex(element => element > 10);
  console.log(result); // Output: 1

除了通过箭头函数传入回调函数,我们也可以使用函数定义的方式来传入回调函数。

function findIndexCallback(element) {
    return element > 10;
  }
  const array1 = [5, 12, 8, 130, 44];
  const result = array1.findIndex(findIndexCallback);
  console.log(result); // Output: 1

三、应用示例1:查找对象中符合条件的元素

在一个对象数组中,我们经常需要查找符合某个条件的对象。这时就可以使用findIndex()方法来实现。

const users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 28 },
    { name: 'Tom', age: 31 },
  ];
  const result = users.findIndex(user => user.age === 28);
  console.log(result); // Output: 1

四、应用示例2:查找字符串在数组中的位置

在一个字符串数组中,我们可以使用findIndex()方法来查找某个字符串在数组中的位置。

const fruits = ['apple', 'banana', 'orange', 'grape'];
  const result = fruits.findIndex(fruit => fruit === 'orange');
  console.log(result); // Output: 2

五、应用示例3:查找包含某个属性的对象

在一个对象数组中,我们可以使用findIndex()方法来查找包含某个属性的对象。

const users = [
    { name: 'John', age: 25, gender: 'male' },
    { name: 'Jane', age: 28, gender: 'female' },
    { name: 'Tom', age: 31 },
  ];
  const result = users.findIndex(user => user.hasOwnProperty('gender'));
  console.log(result); // Output: 0

六、应用示例4:查找字符串中某个字符的位置

在一个字符串中,我们可以使用findIndex()方法来查找某个字符的位置。

const str = 'Hello world';
  const result = str.split('').findIndex(char => char === 'w');
  console.log(result); // Output: 6

七、总结

findIndex()方法是一个非常实用的数组方法,可以帮助我们快速查找符合某个条件的元素。在实际开发中,我们会经常用到它来实现各种功能。

到此这篇关于JavaScript数组方法之findIndex()的用法详解的文章就介绍到这了,更多相关js findIndex()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论