javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS findIndex方法

Web前端JavaScript中findIndex方法使用示例

作者:一只小风华~

这篇文章主要介绍了Web前端JavaScript中findIndex方法使用的相关资料,findIndex() 返回第一个符合条件的数组子项的下标,找到符合条件的之后就不在继续遍历,需要的朋友可以参考下

1. findIndex是什么?

2. 它的作用(解决了什么问题?)

 想象一下这些场景:

 在这些场景中,你都需要:

  1. 检查每个元素是否符合某个条件。

  2. 找到第一个符合条件的

  3. 得到它的位置(索引),而不是元素本身的值。

findIndex 方法就是被设计出来完美解决这类问题的!它帮你省去了手动写 for 循环遍历、设置标志变量、判断条件、找到后 break 跳出循环这些繁琐的步骤。

3. 如何使用?

findIndex 方法接收一个非常重要的参数:一个回调函数(callback function)。这个函数就是前面说的“测试条件”。它的基本语法是:

const foundIndex = array.findIndex(callbackFunction);

回调函数怎么写?

这个回调函数会被 findIndex 自动调用,通常接收三个参数(后两个可选):

  1. element当前正在被检查的数组元素(必须)。

  2. index: (可选)当前元素的索引。

  3. array: (可选)调用 findIndex 方法的那个数组本身。

最重要的是,这个回调函数需要返回一个布尔值(true 或 false):

4. 举个栗子 

场景: 找学生名单里第一个分数大于 90 的学生位置。

const students = [
  { id: 1, name: '小明', score: 85 },
  { id: 2, name: '小红', score: 92 }, // 第一个 >90 的在这里!
  { id: 3, name: '小刚', score: 78 },
  { id: 4, name: '小丽', score: 95 }
];

// 使用 findIndex
const firstHighScoreIndex = students.findIndex(function(student) {
  // 回调函数:检查当前学生的分数是否大于90
  return student.score > 90;
});

console.log(firstHighScoreIndex); // 输出: 1 (因为小红在数组索引1的位置)

发生了什么?

  1. findIndex 从索引 0(小明)开始调用回调函数:小明.score > 90 -> 85 > 90 -> false -> 继续。

  2. 到索引 1(小红):小红.score > 90 -> 92 > 90 -> true! -> 立刻停止

  3. findIndex 返回 1(小红的索引)。

  4. 后面的小刚和小丽就不会再被检查了。

 更简洁的写法(箭头函数):

const firstHighScoreIndex = students.findIndex(student => student.score > 90);
console.log(firstHighScoreIndex); // 输出: 1

5. 如果没找到呢?

const firstHighScoreIndex = students.findIndex(student => student.score > 100); // 没人分数大于100
console.log(firstHighScoreIndex); // 输出: -1

6. 和它的“亲戚们”对比一下,加深理解

7. 总结 & 关键点

到此这篇关于Web前端JavaScript中findIndex方法使用的文章就介绍到这了,更多相关JS findIndex方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文