獲取 JavaScript 陣列中某個型別第 n 個項的索引
我們需要編寫一個函式 getIndex(),它接收一個數組**arr,**一個字串/數字文字**txt**和一個數字**n**。我們必須返回**txt**在**arr,**中第 n 次出現的索引。如果**txt**沒有出現 n 次,那麼我們必須返回 -1。
因此,讓我們編寫這個函式−
示例
const arr = [45, 76, 54, 43, '|', 54, '|', 1, 66, '-', '|', 34, '|', 5,
76];
const getIndex = (arr, txt, n) => {
const position = arr.reduce((acc, val, ind) => {
if(val === txt){
if(acc.count+1 === n){
acc['index'] = ind;
};
acc['count']++;
}
return acc;
}, {
index: -1,
count: 0
});
return position.index;
};
console.log(getIndex(arr, '|', 3));
console.log(getIndex(arr, 54, 2));
console.log(getIndex(arr, '-', 3));輸出
控制檯中的輸出將為 -
10 5 -1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP