seg*_*ter 35 javascript arrays reduce
我试图将一个大于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);
}
}, []);Run Code Online (Sandbox Code Playgroud)
我期望filteredArr在第一次回调执行时使用空数组初始化,因为这里提供了许多示例.但是当我运行这段代码时,我得到了错误
Cannot read property 'push' of undefined,我在哪里搞砸了?谢谢!
Pau*_*aul 50
您需要return filteredArr.push(collectionElement)从匿名函数返回,以便将其用作下一次调用的previousValue
var collection = [3, 5, 11, 23, 1];
// filter all the elements bigger than 10 to a new array
var output = collection.reduce(function(filteredArr, collectionElement) {
if (collectionElement > 10) {
filteredArr.push(collectionElement);
}
return filteredArr;
}, []);
Run Code Online (Sandbox Code Playgroud)
Array.prototype.push将返回新数组的长度.你需要返回累加器.一个简洁的方法是使用Array.prototype.concat,因为该方法实际上将返回数组:
var collection = [3, 5, 11, 23, 1];
var output = collection.reduce(function(filteredArr, collectionElemet) {
if (collectionElemet > 10) {
return filteredArr.concat(collectionElemet);
}
}, []);
Run Code Online (Sandbox Code Playgroud)
您必须返回累加器,以便下一次迭代可以使用累加器的值.
| 归档时间: |
|
| 查看次数: |
10375 次 |
| 最近记录: |