【问题标题】:Function will log value but return undefined函数将记录值但返回未定义
【发布时间】:2020-11-23 03:38:43
【问题描述】:

下面的函数将记录newData 的值,但在调用时返回undefined。有谁知道这可能是为什么?此外,我们将非常感谢您对函数本身的任何反馈!

export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
  let newData = [];
  let i = 0;
  for(const item of data) {
    let time;
    let index = 0
    timeKey.map(key => {
      time ? time = time[key] : time = item[key];
      index++
      if(index === timeKey.length) {
        if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
          newData.push(item)
        };
        i++;
        if(i === data.length) {
          console.log(newData);
          return (newData);
        }
      }
    })
  }
}

【问题讨论】:

  • 你永远不会真正返回 newData。你映射它,但从不返回它。请注意,在映射方法中返回不计算在内。 Map 返回一个新数组,其中您返回的值取代了原始数组的成员。但如前所述,你永远不会用它做任何事情。
  • 如果您只是在最后一个大括号之前添加了return newData;,我很确定您的代码会按照您的预期工作。尽管如此,当您从未真正使用过结果时,我不会使用.map();我会使用.forEach()

标签: javascript arrays for-loop return undefined


【解决方案1】:

map函数通常用于转换集合并存储结果,例如:

var squares = [2, 3, 4].map(x => { return x * x });
// result is squares = [4, 9, 16]

forEach 函数更适合在这里使用,因为您只想循环遍历数组而不关心存储转换。

然后当外循环完成时你的函数可以返回newData

export const filterByDateTimeRange = (data=[{}], timeKey=[], startTime=moment(), stopTime=moment()) => {
  let newData = [];
  let i = 0;
  for(const item of data) {
    let time;
    let index = 0
    timeKey.forEach(key => {                         //changed to a forEach loop
      time ? time = time[key] : time = item[key];
      index++
      if(index === timeKey.length) {
        if(moment(time).isBetween(startTime, stopTime, undefined, '[)')) {
          newData.push(item)
        };
        i++;
        if(i === data.length) {
          console.log(newData);
        }
      }
    });
  }
  return newData; //add the return after your loop finishes
}

【讨论】:

    【解决方案2】:

    这在 map 函数中返回。不返回 filterByDateTimeRange()。如果你想返回 newData.用for循环替换map函数。

    地图:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多