【问题标题】:In Javascript, why am I able to print the value of a forEach but not return the value? [duplicate]在 Javascript 中,为什么我能够打印 forEach 的值但不能返回值? [复制]
【发布时间】:2021-03-20 23:10:51
【问题描述】:
const weatherCodes = {
    thunderstorm: range(200, 232),
    drizzle: range(300, 321),
    rain: range(500, 531),
    snow: range(600, 622),
    atmosphere: range(701, 781),
    clear: [800],
    cloudy: range(801, 804)
  };

  const getWeatherCode = () => {
    for (let key in weatherCodes) {
      let obj = weatherCodes[key];
      obj.forEach((element) => {
        if (element === weather.weatherID) {
          console.log(key);
        }
      });
    }
  };

  getWeatherCode(); // cloudy

我正在从 API 获取 weatherID (804)。

但是,如果我将“console.log(key)”更改为“返回键”,那么当我将函数分配给变量时,我会得到未定义。

【问题讨论】:

    标签: javascript arrays for-loop undefined


    【解决方案1】:

    forEach 没有返回值。如果您想返回一个值,请尝试改用map

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多