基本实现:
//统计countStr() {var str = 'abcabca';var result = {};for (var i = 0; i < str.length; i++) {//判断result是否有该字符if (result[str[i]]) {result[str[i]]++;} else {result[str[i]] = 1;}}console.log('result', result);},
优化:
//统计
countStr() {var str = 'abcabca';var result = str.split('').reduce(function (a, b) {if (a[b]) {a[b]++;} else {a[b] = 1;}return a;}, {});console.log('result', result);
},
顶级优化
//统计
countStr() {var str = 'abcabca';var result = str.split('').reduce((a, b) => (a[b]++ || (a[b] = 1), a), {});console.log('result', result);
},
核心知识点:
reduce函数的用法:
var result = arr.reduce(function(a,b){return a+b;
},0)
若arr[1,2,3]
(1)其中0为初始值,赋值给a,a =0;b为传进来的值,b=arr[i]=1; return a+b=>return 1,此时将return的1赋值给a ,a=1;
(2)a=1,b=2, return a+b=>return 3,此时a = 3;
(3)a = 3,b = 3,reurn a+b => return 6,此时a=6