Es6的休息和传播方式是如何工作的 [英] How Es6 rest and spread is working
问题描述
我现在有以下代码
var _ = require('underscore');
var raw =[
{
key :"name",value:"henry"
},
{
key :"age",value:"old"
},
{
key :"food",value:"matooke"
},
{
key :"kids",value:"Acacia"
},
{
key :"garbageA",value:"kasailoA"
},
{
key :"garbageB",value:"kasasiroB"
},
]
const endShape = _(raw)
.filter(({key}) =>!/garbage/.test(key))
.map(({key,value})=>({[key]:value}))
.reduce((acc,curr)=>({...curr, ...acc}));
console.log(endShape);
代码运行良好,我正在学习一个教程. 我了解.map()方法. 尽管我没有清楚地解释什么
The code works well and I was following a tutorial. I understand up to the .map() method. Though I have failed to get a clear explanation of what
.reduce((acc,curr)=>({...curr, ...acc}));
在做.如何得出这个正确的结果?
is doing. How does is come up with this correct result ?
{ kids: 'Acacia', food: 'matooke', age: 'old', name: 'henry' }
推荐答案
基本上,map
函数输出以下内容:
Basically, the map
function outputs this:
[
{
name: 'henry'
},
{
age: 'old'
},
{
food: 'matooke'
},
{
kids: 'Acacia'
}
]
reduce
然后将像Object.assign
一样工作.它将遍历上面的数组,并将每个键/值对添加到累积对象,该对象在开始时是一个空对象.这就是为什么你得到:
The reduce
will then work like an Object.assign
. It will iterate through the array above and add each key/value pairs to the accumulating object, which is an empty object at the start. That's why you get:
{ kids: 'Acacia', food: 'matooke', age: 'old', name: 'henry' }
开始时,累积对象为undefined
,但由于解构而无关紧要:
The accumulation object is undefined
at start but it doesn't matter thanks to the destructuring:
const foo = undefined;
const bar = { a: 'b' };
console.log({...foo, ...bar })
这篇关于Es6的休息和传播方式是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!