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

array.prototype.reduce: Pushing string value to empty array within arrow function

我有以下代码将数组缩减为没有字母 '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 未定义,我找不到任何解决方案。

您的代码无法运行,因为您没有 return 数组。但是你应该使用 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);