我有以下代码可以将数组缩减为数字而不用字母' 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
未定义,我无法找到解决方法。
答案 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);