函数将记录值,但返回未定义

时间:2020-08-03 03:09:44

标签: javascript arrays for-loop return undefined

下面的函数将记录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);
        }
      }
    })
  }
}

2 个答案:

答案 0 :(得分:2)

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
}

答案 1 :(得分:0)

此返回值在map函数内部。不返回filterByDateTimeRange()。如果要返回newData。用for循环替换map函数。

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