[英]Array.reduce - strange behaviour with objects
myArr = ['a', 'b', 'c' ]; myArr.reduce((obj, val) => ({ ...obj, [val]: val }));
Based on my understanding, you would expect the reduce to return { a: 'a', b: 'b', c: 'c' }
根据我的理解,您可能希望reduce会返回
{ a: 'a', b: 'b', c: 'c' }
What we actually get back is { 0: 'a', b: 'b', c: 'c' }
我们实际上得到的是
{ 0: 'a', b: 'b', c: 'c' }
I tried putting a log inside to see what is going on with that first item, but the output is: 我尝试将日志放入其中,以查看第一项发生了什么,但输出为:
bc {0: "a", b: "b", c: "c"}
So now the behaviour is even more strange because we don't get any logs for the first val
iteration. 因此,现在的行为更加奇怪,因为第一次
val
迭代没有任何日志。
let myArr = ['a', 'b', 'c' ]; let result = myArr.reduce((obj, val) => ({ ...obj, [val]: val }), {}); console.log(result);
You missed the initial value to reduce
. 您错过了
reduce
的初始值。 When no initial value is supplied, reduce
pops off the first element for this purpose (and indeed no iteration happens; because 1+2+3
has two additions, not three, unless you specify we have to start from 0). 如果没有提供初始值,则为此目的会弹出第一个元素的
reduce
(实际上不会发生迭代;因为1+2+3
有两个加法,而不是三个,除非您指定必须从0开始。)
The first element is "a"
, which deceptively becomes the misnamed obj
; 第一个元素是
"a"
,它看起来像是被错误命名的obj
; when you execute {..."a", b: "b"}
, you will see that ..."a"
expanded in the object context will yield the characters' index as the key; 当执行
{..."a", b: "b"}
,您会看到在对象上下文中扩展的..."a"
将产生字符的索引作为键; thus, ..."a" is equivalent to ...{0: "a"}
. 因此,...“ a”等效于
...{0: "a"}
。
Good thing you didn't try with myArr = ['hello', 'world']
- that'd be much more of a surprise, I imagine (the result from that being {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", world: "world"}
). 您没有使用
myArr = ['hello', 'world']
尝试过的myArr = ['hello', 'world']
-我想这会更令人惊讶(其结果是{0: "h", 1: "e", 2: "l", 3: "l", 4: "o", world: "world"}
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.