获取JavaScript数组中某个类型的第n个项目的索引
我们需要编写一个函数,说它getIndex()接受一个数组arr,一个字符串/数字文字txt和一个Numbern。我们不得不返回的第n个出现的指数TXT的编曲,。如果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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短