JS 计算1-10000中出现的 0 的次数 (经典地使用了ES6中 map, filter, reduce)

1 概述

利用JS 计算1-10000中出现的 0 的次数

2 示例

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)

代码非常地简洁,但是却非常地经典,博主在这里一句一句地给大家剖析!

3 剖析

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

首先创建了一个拥有10000个元素的空数组,利用 fill() 函数初始化,所有的值都为空,再利用 map, 给数组返回 index + 1 ,也就实现了数组赋值,获得了1,到10000的数组;

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

利用 filter 函数 以及正则, 筛选出数字中包含 0 的元素;

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

利用 reduce 函数,初始值为0, 同时利用 正则 match 计算每一个元素中包含 0 的个数,然后 reduce 累加即完成。

非常经典的使用了 map, filter, reduce 函数

猜你喜欢

转载自blog.csdn.net/qq_41800366/article/details/102854093