【问题标题】:How to loop through array with FindIndex from its end?如何使用 FindIndex 从其末尾循环遍历数组?
【发布时间】:2022-01-06 16:48:38
【问题描述】:

我需要得到errorIdx = 3,但我得到了0。如何从数组的末端循环遍历?

  const scrollPosition = 5007
  const errorsHeight = [947, 2498, 3495, 4805, 5755]

  errorIdx = errorsHeight.findIndex((itemHeight: number) => itemHeight < scrollPosition)
  console.log(errorIdx) // 0

【问题讨论】:

  • array.reverse() 反转数组,但如果你想保留原始数组的索引。然后进行克隆并反转它,然后一旦发现它的索引反转,在原始数组中搜索元素
  • @MrJami 正是我要说的
  • 或者使用for循环:for (let i = errorsHeight.length-1; i &gt;= 0; i--) {...}
  • 在这种情况下errorIdx = 1,但我需要它为3 ....不能使用reverse()
  • @qweezz 将我的评论读到最后。你仍然可以得到你的 3。

标签: javascript arrays loops search callback


【解决方案1】:

findLastIndex 的另一种实现,其中回调函数知道 thisArg 上下文/目标,并且还将使用其三个参数([element, index, array])进行调用;从而遵循findIndex的标准...

function findLastIndex(arr, test, target) {
  if (!arr && ((arr ?? true) === true)) {
    throw new TypeError('findLastIndex called on null or undefined');
  };
  if (typeof test !== 'function') {
    throw new TypeError(`${ test } is not a function`);
  };
  if (!Array.isArray(arr)) {
    arr = Array.from(arr);
  }
  target = target ?? null;

  let isContinue = true;
  let idx = arr.length;

  // assures -1 as return value for nothing found.
  while ((idx >= 0) && isContinue) {

    // be aware of sparse array slots ... and ...
    // be a guard for the negative index default.
    if (arr.hasOwnProperty(--idx)) {

      isContinue = !test.call(target, arr[idx], idx, arr);
    }
  }
  return idx;
}

const errorsHeight = [947, 2498, 3495, 4805, 5755];
const scrollPosition = 5007;

console.log(
  findLastIndex(errorsHeight, (height/*, idx, arr*/) =>
    height < scrollPosition
  )
);
console.log(
  findLastIndex(errorsHeight, height => height < 5)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

    【解决方案2】:

    对数组进行排序或反转它会为您的解决方案增加额外的 O(n)。

    简单的方法是创建一个辅助函数,从数组末尾开始查找索引:

    function findLastIndex(arr, comparator){
        for(let i = arr.length - 1; i > 0; i--){
            const valid = comparator(arr[i], i);
            if(valid){
                return i;
            }
        }
    
        return -1;
    }
    
    
    console.log(findLastIndex(errorsHeight, (itemHeight: number) => itemHeight < scrollPosition))
    

    【讨论】:

      【解决方案3】:

      最好用一个简单的 for,像这样:

      const scrollPosition = 5007;
      const errorsHeight = [947, 2498, 3495, 4805, 5755];
      let errorIdx = -1;
      
      for (let i = 0; i < errorsHeight.length; i++)
          if((errorIdx === -1 && errorsHeight[i] < scrollPosition) || (errorIdx >= 0 && errorsHeight[i] < scrollPosition && errorsHeight[i] > errorsHeight[errorIdx]))
              errorIdx = i;
      
      console.log(errorIdx) //3
      ;D

      【讨论】:

        【解决方案4】:

        您可以通过过滤器保留一组匹配项,然后返回该数组的长度。我在这里添加了sort 以确保数组按数字顺序排列。

        const scrollPosition = 5007
        const errorsHeight = [947, 2498, 3495, 4805, 5755]
        
        errorIdx = errorsHeight
                    .sort((a, b) => a - b)
                    .filter(itemHeight => itemHeight < scrollPosition)
                    .length - 1
        console.log(errorIdx) 

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-07-28
          • 1970-01-01
          • 2021-04-02
          • 2013-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多