when to use reduce and reduceRight?

前端 未结 6 2081
野性不改
野性不改 2020-12-17 08:44

Can you describe this for me?

var arr, total;
arr = [1, 2, 3, 4, 5];
total = arr.reduce(function(previous, current) {
return previous + current;
});
// total         


        
6条回答
  •  难免孤独
    2020-12-17 09:10

    Do correct me if I am wrong;

    My understanding is that, solely in the context of Array, the fundamental difference between reduce and reduceRight - other than just the direction - is that in previous moments of history (before browser optimisations etc), compilers would count backwards from 10 to 0, (arr.reduceRight - right-to-left), a lot faster than counting forwards from 0 to 10 (arr.reduce - left-to-right).

    Reducing from the right meant that the compiler could start at 10 and the iterator could only ever get to 0. This meant that the compiler, on each iteration, had to check that the current iteration is greater than 0. Easy peasy.

    However, when reducing from the left (arr.reduce - left-to-right), the length of the collection could possibly change, and thus the compiler having to re-evaluate arr.length on each iteration.

    For an example, if you had an array of 10 using Array(10), and you used arr.reduce() - left-to-right, the compiler would have to check to make sure nothing else is pushed on to the collection during the reduce, in order to determine its position - on each iteration.

    I hope this helps someone :)

提交回复
热议问题