获取 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

更新于:2020 年 8 月 21 日

612 次浏览

启动您的职业

完成课程获得认证

开始
广告
© . All rights reserved.