array.find() 返回项目和索引

K20*_*0GH 6 javascript arrays ecmascript-6

我有一个数据数组,我需要从数组中的某个项目返回数据以及结果的索引:

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

谁能告诉我如何实现我在下面尝试做的事情?

const result = design.data().items.find((e, i, a, arg) => {
  if(e.id === this.props.match.params.item) {
    return {item:e, index: i}
  }
})
Run Code Online (Sandbox Code Playgroud)

Pet*_*roz 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 };
}
Run Code Online (Sandbox Code Playgroud)