根据特定条件查找数组中元素的最后一个索引

新手上路,请多包涵

假设我有一个对象数组:

 [
  { 'a': 'something',     'b':12 },
  { 'a': 'something',     'b':12 },
  { 'a': 'somethingElse', 'b':12 },
  { 'a': 'something',     'b':12 },
  { 'a': 'somethingElse', 'b':12 }
]

获取元素最后一个索引的最干净方法是什么 a 的值为 'something' - 在本例中为索引 3?有什么办法可以避免循环吗?

原文由 Jacob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 469
1 个回答

这是一个可重用的打字稿版本,它反映了 ES2015 findIndex 函数的签名:

 /**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param array The source array to search in
* @param predicate find calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
*/
export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number {
    let l = array.length;
    while (l--) {
        if (predicate(array[l], l, array))
            return l;
    }
    return -1;
}

原文由 Nico Timmerman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题