2019-09-10 14:12:22 3624浏览
今天千锋扣丁学堂HTML5培训老师给大家分享一篇关于es6中reduce基本使用方法的详细介绍,首先想到为啥要把es6中reduce单独拿出来说呢?下面我们一起来看一下吧。
	
	
var total = [ 0, 1, 2, 3 ].reduce(( acc, cur ) => {
 return acc + cur
}, 0);
console.log(total) // 6
var array = [[1, 2], [3, 4], [5, 6]].reduce(( acc, cur ) => {
  return acc.concat(cur)
}, []);
console.log(array) // [ 0, 1, 3, 4, 5, 6 ]
let names = ['tom', 'jim', 'jack', 'tom', 'jack'];
const countNames = names.reduce((allNames, name) => {
 if (name in allNames) {
  allNames[name] ++;
 }
 else {
  allNames[name] = 1;
 }
 return allNames;
}, {});
 
console.log(countNames) // { tom: 2, jim: 1, jack: 2 }
const arraySum = (arr, val) => arr.reduce((acc, cur) => {
  return cur == val ? acc + 1 : acc + 0
}, 0);
 
let arr = [ 0, 1, 3, 0, 2, 0, 2, 3 ]
console.log(arraySum(arr, 0)) // 数组arr中 0 元素出现的次数为3
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((init, current) => {
  if (init.length === 0 || init[init.length - 1] !== current) {
    init.push(current);
  }
  return init;
}, []);
console.log(result); //[1,2,3,4,5]
// console.log(...new Set([1,2,3,4,5,2,4,1]))
const dedupe = (array) => {
  return Array.from(new Set(array));
}
console.log(dedupe([1, 1, 2, 3])) //[1,2,3]
	
	
                           
  
	
【关注微信公众号获取更多学习资料】 【扫码进入HTML5前端开发VIP免费公开课】