代码之家  ›  专栏  ›  技术社区  ›  K20GH

数组.查找()返回项目和索引

  •  0
  • K20GH  · 技术社区  · 7 年前

    我下面的代码返回的是数据,但不是索引,所以我认为这根本不能正常工作。

    有人能告诉我如何才能实现我下面要做的事吗?

    const result = design.data().items.find((e, i, a, arg) => {
      if(e.id === this.props.match.params.item) {
        return {item:e, index: i}
      }
    })
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Petr Broz    7 年前

    你可以用 findIndex find 方法。

    const { items } = design.data();
    const id = items.findIndex((e) => e.id === this.props.match.params.item);
    if (id !== -1) {
      return { item: items[id], index: id };
    }
    
        2
  •  2
  •   Ori Drori    7 年前

    findIndex -1 (找到一个项),它返回该项和索引:

    const findWithIndex = (arr, predicate) => {
      const index = arr.findIndex(predicate);
        
      return {
        item: index !== -1 ? arr[index] : null,
        index
      };
    };
    
    const arr = [{ id: 1}, { id: 2 }, { id: 3 }];
    
    const result = findWithIndex(arr, ({ id }) => id === 2);
    
    console.log(result);

    代码的用法示例:

    findwithIndex(design.data().items, e => this.props.match.params.item);
    
        3
  •  1
  •   Chandru    7 年前

    Array.findIndex 获取元素的索引。然后使用索引可以从数组中获取元素

    const items = design.data().items;
    const index = items.findIndex(item => item.id === this.props.match.params.item);
    console.log(index);  // gives index
    console.log(items[index]);  // gives the element