作为练习,我正在尝试将地图示例转换为使用reduce:
const numbers = [1, 2, 3, 4];
numbers.map(function(a,b) {
return a+b;
});
// [1, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)
我尝试使用reduce的相同示例:
numbers.reduce(
(sum, elem) => {
sum.push(elem + elem); // how can one add the index of array to the number instead of doubling it?
return sum;
}, []);
// [2, 4, 6, 8], instead I want: [1, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)
你的结果减少了.传递第三个参数,即索引
const numbers = [1, 2, 3, 4];
var arr = numbers.reduce(
(sum, elem, index) => {
sum.push(elem + index);
return sum;
}, []);
console.log(arr);Run Code Online (Sandbox Code Playgroud)
但
您的map功能只能通过意外:)正常工作.
map 函数接受的参数不是2个兄弟项目,而是项目及其索引.
看这里.如果您更改前一个项目,您将获得其他行为.在你的逻辑中,最后一项必须是11,如果它接受2个兄弟项目,但不是它仍然是7,因为它接受项目和它的索引.
更改数据的示例.
1 -> 1 + 0 (index) = 1
2 -> 2 + 1 (index) = 3
3 -> 3 + 2 (index) = 5
4 -> 4 + 3 (index) = 7
Run Code Online (Sandbox Code Playgroud)
const numbers = [1, 2, 7, 4];
var arr = numbers.map(function(a,b) {
return a+b;
});
console.log(arr);Run Code Online (Sandbox Code Playgroud)
产量
1 -> 1 + 0 (index) = 1
2 -> 2 + 1 (index) = 3
7 -> 7 + 2 (index) = 9
4 -> 4 + 3 (index) = 7
Run Code Online (Sandbox Code Playgroud)
reduce 函数接受它的基本形式两个参数,数组的项和上一次迭代的返回值.
所以我认为你不太了解这些功能.
您可以在Array#map()和Array#reduce()中阅读更多内容
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |