一段代码统计字符串中重复单词的思考

统计重复字符

  看到一段代码,使用了reduce方法统计字符串中重复单词,现在我简化直接对数组进行操作,说说这么做的原理是什么。

1
2
3
4
5
6
var arr=["a","b","c","b","a"]; 

arr.reduce(function(prev,next){
prev[next]=(prev[next]+1)||1;
return prev;
},{});

arr.reduce(callback[, initialValue])

回调函数第一次执行时,

1
2
3
4
5
6
7
8
9
callback(previousValue, currentValue,currentIndex,array)

- previousValue(上一次调用回调函数时的返回值,或者初始值)

- currentValue(当前正在处理的数组元素)

- currentIndex(当前正在处理的数组元素下标)

- array(调用reduce()方法的数组)

  回调函数第一次执行时,

  • 如果reduce有initialValue参数,那么 previousValue 等于 initialValue ,并且currentValue 等于数组中的第一个值;

  • 如果reduce没有 initialValue 参数,那么previousValue 等于数组中的第一个值,currentValue等于数组中的第二个值。

再来看上面的那段代码,我试着输出了prev ,它是一个数组,在每一次循环中的结果时这样的

1
2
3
4
5
{a: 1}
{a: 1, b: 1}
{a: 1, b: 1, c: 1}
{a: 1, b: 2, c: 1}
{a: 2, b: 2, c: 1}

next 则为每次循环的 currentValue

所以运行的过程应该是这样的:

  1. reduce参数获得了一个回调函数和一个空的对象作为初始值,在第一次回调时,
    prev={}    next=”a”     prev[“a”]=undefined||1
    然后返回prev这个数组,作为下一次的prev。

  2. next=”b” prev[“b”]=1    ……如此循环

对字符串的操作

1
2
3
4
5
6
7
var str="abcscd",
arr=str.split('');

arr.reduce(function(prev,next){
prev[next]=(prev[next]+1)||1;
return prev;
},{});

Copyright © 2018 - 2019 诗之花绪 All Rights Reserved.

UV : | PV :