Javascript interview classic routine reduce function duplicate checking

  • 2021-08-05 08:53:13
  • OfStack

Today, I accidentally saw a piece of code. The code used a short space to complete the classic interview question of string statistics of the same character times, in which reduce was used. After checking it online, I didn't find anything valuable, which led to a waste of my time to understand it. Now my thoughts are sorted out as follows:

Original code:


var arr="qweqrq"
var info= arr.split('').reduce((a,b)=>
 (a[b]++ || (a[b]=1),a)
,{})
console.log(info)

The idea of the code is as follows: First, the string arr is cut into an array by split method, and then reduce is used. What does this method do? It is divided into these steps:

1. First, reduce will receive 1 callback to execute on every 1 element in the array, if there is a second parameter as in the above example: {}. callback will use this {} as a parameter to pass callback with the first element 1 in the array;

2. After the parameter is passed in, an AND gate short-circuit operation will be performed, which can also be called default value operation. When a [b] + + comes true, a [b] will be returned. Here, a is {} and b is "q". Obviously, there is no b in a. If a [b] = 1, a [b] will be assigned a value of 1, followed by a comma expression, so a object with a [b]: 1 will be returned.

Short-circuit operation of AND gate: If the value of the first operand is true, short-circuit operation will directly generate the value of the first operand. If it is false, the value of the second operand is generated.

Comma expression: The general form of a comma expression is: Expression 1, Expression 2, Expression 3... Expression n. The comma expression is solved by first evaluating the value of expression 1, then evaluating the value of expression 2, … 1 straight to the value of expression n. Finally, the value of the whole comma expression is the value of the expression n.

3. To talk about the reduce function later, it can continue the result returned after the previous execution as a parameter and execute it with the following element 1 passed into callback, which is equivalent to fn (fn (fn (fn (a, b), c), d), e), and fn is callback;

4. In this example, callback is executed six times because the second parameter {} is passed in. It is equivalent to entering and duplicate checking every element in the array. For example, when callback runs to the fourth time, a is {q: 1, w: 1, e: 1}, callback is executed, a [b] means a ['q'] exists, a ['q'] + +, a ['q'] is executed, and so on.

It should be noted that reduce is a method introduced by es5, and ie8 and below are incompatible.


Related articles: