【问题标题】:return the first index with forEach使用 forEach 返回第一个索引
【发布时间】:2023-01-17 23:18:06
【问题描述】:

我有一堆怪物。怪物是一个对象,例如

{
type: "FIRE",
name: "Sosa",
original: true,
food: ["meet","egg"] // cannot contains 2 identical food
}

我想要的是返回第一个有 X 食物的怪物的索引我试过这个函数:

let x = "meet";
let index = -1;
let i = -1;
animals.forEach((animal) => {
  i++;
  animal.food.forEach((food) => {
    if (food === "x") index = i;
  });
});
return index;

这并不适用于所有情况。我是编程新手,请提供一些解释和帮助,我将不胜感激

【问题讨论】:

  • 如果你想寻找数组中的某些内容您应该使用 find 方法,而不是 forEach
  • 我是初学者,我正在学习 forEach 这就是为什么

标签: javascript arrays foreach


【解决方案1】:

您的代码返回最后找到的项目的 index 而不是第一个。因此它仅在最后找到的项目同时是第一个找到的项目时才有效,即只找到一个项目。

如果你真的想使用forEach,另一种方法是存储所有找到的索引:

var foundIndexes = [];

// your code 
if(food === 'x') foundIndexes.push(i);
//your code

const myIndex = foundIndexes.length == 0 ?  -1 : foundIndexes[0] // that means if the array is still empty myIndex = -1 else myIndex = the first element of foundIndexes ie the first found index
return myIndex;

您也可以使用array.findIndex它完全符合您的要求,甚至可以使用array.every在找到第一项后停止循环

【讨论】:

【解决方案2】:

您可以将 Array#findIndexArray#includes 结合使用。

let idx = animals.findIndex(a => a.food.includes('x'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多