一、findIndexOf概述
findIndexOf
方法是JavaScript中很常用的一個數組方法,它用於查找數組中某個元素的索引值,並返回找到的第一個匹配項的索引,如果沒有匹配項,則返回-1。該方法是ES6新增的方法。
二、findIndexOf語法
array.findIndex(callback(element[,index[,array]])[,thisArg])
callback
:處理數組中每個元素。該函數的返回值必須是布爾值。它接受三個參數:element、index和array。thisArg
:在執行callback
函數時使用的this值。
三、使用findIndexOf方法查找元素
下面是一個例子,展示如何使用findIndexOf
方法查找數組中的元素並返回索引:
const arr = [1, 2, 3, 4, 5]; const index = arr.findIndex(element => element === 4); console.log(index); // 3
四、使用findIndexOf方法查找對象中的元素
不僅可以在數組中查找元素,還可以在對象數組中查找元素。下面的例子顯示了如何使用findIndexOf
方法查找對象數組中的元素並返回索引:
const people = [ {name: 'Alice', age: 25}, {name: 'Bob', age: 30}, {name: 'Charlie', age: 35}, ]; const index = people.findIndex(person => person.name === 'Bob'); console.log(index); // 1
五、findIndexOf回調函數
回調函數在執行findIndexOf
方法時使用。下面是一些回調函數的例子:
1. 查找第一個大於10的數字的位置
const arr = [5, 2, 8, 11, 3]; const index = arr.findIndex(element => element > 10); console.log(index); // 3
2. 查找第一個符合條件的字符串的位置
const arr = ['apple', 'orange', 'banana', 'peach']; const index = arr.findIndex(element => element.length === 6); console.log(index); // 0
3. 查找屬性值等於指定值的對象的位置
const people = [ {name: 'Alice', age: 25}, {name: 'Bob', age: 30}, {name: 'Charlie', age: 35}, ]; const index = people.findIndex(person => person.name === 'Bob'); console.log(index); // 1
六、findIndexOf方法的返回值
findIndexOf
方法返回第一個滿足條件的數組元素的索引位置,如果沒有找到,則返回-1。下面的例子演示了查找數組中不存在元素的情況:
const arr = [1, 2, 3]; const index = arr.findIndex(element => element === 4); console.log(index); // -1
七、結論
findIndexOf
方法在JavaScript中是比較常用的一個數組方法,用於查找數組中的元素並返回它的索引值。它可以應用於各種數據類型的數組和對象數組中,其使用方法也各有不同。熟練掌握該方法可以大大提高JavaScript編程效率。
原創文章,作者:PHUEZ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/332991.html