欢迎光临 - 我的站长站,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!

js教程

find findIndex indexOf索引选择器使用方法

js教程 我的站长站 2024-01-13 共9人阅读

find使用方法

find方法是ES6引入的一种数组方法,可以用来查找数组中符合条件的元素。

语法是:

array.find(callback(element[, index[, array]])[, thisArg])

callback是一个函数,用来测试每个元素是否符合条件。callback函数接收三个参数,分别是当前遍历的元素、元素的索引、原数组本身。当找到符合条件的元素时,find方法会返回该元素的值。如果没有找到符合条件的元素,则返回undefined。

例如:使用find方法查找数组中第一个>6的元素

const numbers = [1, 3, 5, 7, 9];
const result = numbers.find(element => element > 6);
console.log(result); // 7

在callback函数中,我们使用箭头函数语法,检查每个元素是否>6,因为7是第一个>6的元素,索引find方法返回7作为结果。  

findIndex使用方法

findIndex方法也可用来查找数组中符合条件的元素,返回符合条件的元素在数组中的索引。

语法:

array.findIndex(callback(element[, index[, array]])[, thisArg])

当找到符合条件的元素时,findIndex方法会返回该元素在数组中的索引。如果没有找到符合条件的元素,则返回-1。

例如:使用findIndex方法查找数组中第一个>6的元素的索引

const numbers = [1, 3, 5, 7, 9];
const result = numbers.findIndex(element => element > 6);
console.log(result); // 3

因为7是第一个>6的元素,他的索引是3,所以findIndex方法返回3作为结果。

indexof使用方法

indexof方法,可以用来查找数组中指定元素的位置。

语法:array.indexOf(searchElement[, fromIndex])

searchElement是要查找的元素,fromIndex是可选参数,表示从哪个索引开始查找。当找到指定元素时,indexof方法会返回该元素所在数组中的索引,如果没有找到则返回-1。

例如:使用indexof方法查找数组中7的索引

const numbers = [1, 3, 5, 7, 9];
const result = numbers.indexOf(7);
console.log(result); // 3

因为7的索引是3,所以indexof方法返回3作为结果。