我正在尝试将数组中大于10的所有元素筛选到一个新的数组中。我有意不使用Array.prototype.filter()
,因为我想学习reduce()
方法。这是我正在尝试的代码:
var collection = [3, 5, 11, 23, 1];
// fileter all the elements bigger than 10 to a new array
var output = collection.reduce(function(filteredArr, collectionElemet) {
if (collectionElemet > 10) {
return filteredArr.push(collectionElemet);
}
}, []);
我原本期望在第一次回调执行时,filteredArr
被初始化为空数组,就像许多例子中提供的这里一样。但是当我运行这段代码时,我得到了错误 Cannot read property 'push' of undefined
,我搞错了什么?谢谢!
Array.prototype.filter
,你当前的代码很丑陋和误导性。 - zerkmsfilter
,但正在尝试理解reduce
。 - Amadan