JS calculates the number of occurrences of 0 in 1-10000 (classic use of map, filter, reduce in ES6)

1 Overview

Use JS to calculate the number of 0s in 1-10000

2 Example

let res = new Array(10000).fill('').map((_, index) => index + 1)
        .filter(item => /0/.test(item))  // 返回包含零的
        .reduce((count, item) => {
    
       // 计数  初始值0
            return count + (String(item).match(/0/g) || []).length
            }, 0);
console.log(res)

The code is very concise, but it is very classic. The blogger will analyze it sentence by sentence!

3 Analysis

new Array(10000).fill('').map((_, index) => index + 1)

First, an empty array with 10,000 elements is created, initialized with the fill() function, all values ​​are empty, and then map is used to return index + 1 to the array, and the array assignment is realized, and 1 to 10000 is obtained The array;

.filter(item => /0/.test(item)) 

Use the filter function and regularity to filter out the elements that contain 0 in the number;

.reduce((count, item) => {
    
       // 计数  初始值0
            return count + (String(item).match(/0/g) || []).length
            }, 0);

Using the reduce function, the initial value is 0, and the regular match is used to calculate the number of 0 in each element, and then the reduce accumulation is completed.

Very classic use of map, filter, reduce functions

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/102854093