获取 JavaScript 数组中某个类型的第 n 个项目的索引
javascriptweb developmentobject oriented programming更新于 2025/10/2 1:16:17
我们需要编写一个函数,比如 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

