Why doesn't abbreviation print the first value?

I am trying to learn how to use the abbreviation here, and this will only be logged. b,c,d

['a', 'b', 'c', 'd'].reduce(function(acc, cur){
  console.log(cur);
  return cur;
})

I do not understand what a battery is. I do not know how this works even after reading the documentation.

Currentdoes not appear as Currentbecause it is 'a'skipped.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Edit: here is the best set of test cases:

enter image description here

+4
source share
6 answers

reduce , , () .

, [a, b, c, d].reduce(f), :

   f(a, b)
-> f(f(a, b), c)
-> f(f(f(a, b), c), d)

, a .

( index array, f)

" ", , , - . , , , acc cur "a" "b"

reduceRight :

   f(c, d)
-> f(b, f(c, d))
-> f(a, f(b, f(c, d)))
+8

initialValue, , API Array#reduce.

InitialValue

[] . , . - .

['a', 'b', 'c', 'd'].reduce(function(acc, cur){
    console.log(cur);
    return cur;
}, undefined);
// ^^^^^^^^^
Hide result
+5

, , , :

let products = [
    { label: 'Product 1', price: 5  },
    { label: 'Product 2', price: 15 },
    { label: 'Product 3', price: 20 },
];

:

let totalPrice = products.reduce((acc, product) => {
    return acc + product.price;
}, 0); // 0 - initial value

console.log(totalPrice);

a, , .

+1

- [0], - [1].

- f ([0], [1]), - [2] ..

0

docs,

reduce() ( ), .

,

['a', 'b', 'c', 'd'].reduce(function(acc, cur){
  console.log(cur);
  return cur;
})

reduce acc a,b,c cur b,c,d

, a,b b,c, c,d

0

,

['a', 'b', 'c', 'd'].reduce(function(acc, cur){
  console.log(acc);
  return acc+cur;
})

:

ab
abc
abcd

array.reduce() . () . Accumulator .

0

Source: https://habr.com/ru/post/1675075/


All Articles