Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用reduce的Javascript重构映射示例_Javascript - Fatal编程技术网

使用reduce的Javascript重构映射示例

使用reduce的Javascript重构映射示例,javascript,Javascript,作为练习,我尝试将地图示例转换为使用reduce: const numbers = [1, 2, 3, 4]; numbers.map(function(a,b) { return a+b; }); // [1, 3, 5, 7] 我尝试使用reduce执行相同的示例: numbers.reduce( (sum, elem) => { sum.push(elem + elem); // how can one add the index of array to th

作为练习,我尝试将地图示例转换为使用reduce:

const numbers = [1, 2, 3, 4];

numbers.map(function(a,b) {
    return a+b;
});
// [1, 3, 5, 7]
我尝试使用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]

使用reduce获得的结果。传递第三个参数,即索引

const number=[1,2,3,4];
var arr=numbers.reduce(
(总和、元素、索引)=>{
推送总和(元素+索引);
回报金额;
}, []);

控制台日志(arr)您可以添加上一项,并检查真实性和实际项目。返回包含指定值的数组

var number=[1,2,3,4],
结果=数字。减少((r,a,i,aa)=>r.concat((aa[i-1]| | 0)+a),[]);

控制台日志(结果)嗯,我只是想用reduce得到与map示例相同的结果。在你的回答中,你详细阐述了地图示例,但没有回答我的问题。