【问题标题】:forEach is returning undefinedforEach 正在返回未定义
【发布时间】:2020-01-19 05:22:18
【问题描述】:

我希望我的 foreach() 循环遍历一组映射并检查类型值是否匹配。如果不返回 else 语句。

功能

function checkCars(carData) {
        const cars = carData.models;

        models.forEach(model => {
            if (model.type === 'Toyota' || model.type === 'Hyundai') {
                return "Type A";
            } else {
                return "Type B";
            }
        });
    }

数据库

"models": [
  {type: "Toyota"}
  {type: "Hyundai"}
  {type: "Audi"}
  {type: "VW"}
]

【问题讨论】:

  • 您正在迭代模型而不是汽车。
  • 使用另一个变量来保存类型并为每个 in 函数返回该类型
  • 最好提供您预期的输出。
  • 这能回答你的问题吗? Can forEach in JavaScript make a return?

标签: javascript loops


【解决方案1】:

Array.prototype.forEach()的返回值为undefined,你不能从forEach()显式返回任何东西。

您可以尝试改用Array.prototype.map()

map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

function checkCars(carData) {
  const cars = carData.models;

  return models.map(model => {
    if (model.type === 'Toyota' || model.type === 'Hyundai') {
      return "Type A";
    } else {
      return "Type B";
    }
  });
}

【讨论】:

  • 当第一个if 为真时如何打破循环?
  • @aszet,你甚至不能停止循环,它们必须为数组中的所有元素执行。要打破循环,您必须使用简单的 for 循环。
  • @aszet 如果你想要一些,使用.some(),如果你想要全部使用.every()。有关示例,请参阅documentation
【解决方案2】:

forEach 没有返回值。您应该使用map 函数来更改元素的类型。

【讨论】:

    【解决方案3】:

    如果你想转换数组,你想要map:

    function checkCars(carData) {
      const cars = carData.models;
    
      return models.map(model => {
        if (model.type === 'Toyota' || model.type === 'Hyundai') {
          return "Type A";
        } else {
          return "Type B";
        }
      });
    }
    

    【讨论】:

    • 那么,您将不得不更具体地了解问题所在。你想要什么输出
    【解决方案4】:

    你可以这样使用:

    function checkCars(carData) {
            const cars = carData.models;
            let type = "Type A"
            models.forEach(model => {
                if (model.type !== 'Toyota' && model.type !== 'Hyundai') {
                    type = "Type B";
                }
            });
            return type
        }
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多