箭头函数预期返回值

时间:2020-08-20 16:29:51

标签: javascript arrays reactjs

如何解决此警告?我使用.map的方式有误吗?

我试图显示通过另一个包含该信息的数组所收到的每个月的总销售额和总收入,以便以后在图表上显示。

var arrEneSales = [0, 0, 0, 0, 0, 0];
var arrJulSales = [0, 0, 0, 0, 0, 0];

var arrMoneyEne = [0, 0, 0, 0, 0, 0];
var arrMoneyJul = [0, 0, 0, 0, 0, 0];

this.state.sales.map((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
});

2 个答案:

答案 0 :(得分:1)

Map用于返回数组。如果您不希望返回任何内容,而只是通过数组进行迭代,则不要像这样使用mapforEach

this.state.sales.forEach((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
});

这样的地图工作。

var returnedArray = this.state.sales.map((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
  return item;
});

答案 1 :(得分:1)

根据类型定义

/**
 * Performs the specified action for each element in an array.
 * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
 * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
 */
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;

/**
 * Calls a defined callback function on each element of an array, and returns an array that contains the results.
 * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
 */
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

因此,您看到map函数应该返回一个数组。 您应该使用forEach,该结果什么也不返回

访问MDN获取有关地图功能的javascript文档