array.prototype.reduce:将字符串值推送到箭头函数中的空数组

时间:2016-08-07 15:04:23

标签: javascript arrow-functions

我有以下代码可以将数组缩减为数字而不用字母' e'

var numbers = ["one", "two", "three", "four", "five", "six",
               "seven", "eight", "nine", "ten", "eleven"];
var reduced = numbers.reduce(function(reducedArray, number) { 
  if (number.toString().indexOf("e") === -1) {
    reducedArray.push(number); 
  }
  return reducedArray; 
}, []);

一切都很好。但现在我想在箭头函数中使用相同的代码

var reduced = numbers.reduce((reducedArray, number) => {
  if (number.indexOf('e') === -1) {
    reducedArray.push(number);
  }
}, []);

但这不起作用,因为reducedArray未定义,我无法找到解决方法。

1 个答案:

答案 0 :(得分:3)

您的代码无效,因为您没有返回数组。但您应该使用filter代替:

var numbers = ["one", "two", "three", "four", "five", "six",
               "seven", "eight", "nine", "ten", "eleven"];
var reduced = numbers.filter(number => !number.includes("e"));
console.log(reduced);