admin管理员组文章数量:1207738
I was wondering why the index in array.reduce()
starts from 1 rather than 0 in the below example
([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11
I was wondering why the index in array.reduce()
starts from 1 rather than 0 in the below example
([11,22,33,44]).reduce((acc, val, index) => console.log(val));
//This outputs 22, 33 and 44 and skips 11
Share
Improve this question
edited Sep 4, 2019 at 18:21
Saksham
asked May 2, 2019 at 18:13
SakshamSaksham
9,3809 gold badges46 silver badges75 bronze badges
1
- 6 If you don't pass a second argument, it starts at element 1 and passes element 0 as the accumulator value. – Pointy Commented May 2, 2019 at 18:14
2 Answers
Reset to default 19The accumulator takes the first value if you don't pass a value as the second argument:
// add a vlaue to start
([11,22,33,44]).reduce((acc, val, index) => console.log(val), 0);
// now all values are iterated
If you log the accumulator you can see how all the values are used without the second arg:
// Show accumulator return value
let final = ([11,22,33,44]).reduce((acc, val, index) => (console.log("acc:", acc, "val:", val), val));
// final is the last object that would have been the accumulator
console.log("final:", final)
Cause .reduce
is designed to work without an initial accumulator:
[1, 2, 3].reduce((a, b) => a + b)
For this to work, a
will be the first element and b
the second one at the first iteration, the next one will take the previous result and the third value.
If you pass an initial accumulator as the second argument, it will start at index 0.
本文标签: javascriptWhy arrayreduce() starts from index 1Stack Overflow
版权声明:本文标题:javascript - Why `array.reduce()` starts from index 1 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738745633a2110103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论