做统计用的,不会改变原数组
参数:每一次的返回值将作为下一次pre的初始值,pre可以设置默认值,cur是当前项
console.log([1, 2, 3, 4].reduce((pre, cur) => pre + cur))
let arr = ['name', 'age', 'long', 'short', 'long', 'name', 'name'] let times = arr.reduce((pre, cur) => { if (cur in pre) { //判断对象中是否包含这个属性 pre[cur]++ } else { pre[cur] = 1 //因为一开始进入的是这里,所以它能进行++操作 } return pre }, {}); //{} 是赋给pre的默认值 console.log(times); //{ name: 3, age: 1, long: 2, short: 1 }
let arr = ['name', 'age', 'long', 'short', 'long', 'name', 'name'] let times = arr.reduce((pre, cur) => { if (!pre.includes(cur)){ //这个方法一般人我不告诉他 pre.push(cur) } return pre }, []); console.log(times);
let ToDos= [ {id: '001',name: '抽烟',completed: true}, {id: '002',name: '喝酒',completed: false}, {id: '003',name: '烫头',completed: true} ] console.log(ToDos.reduce((pre, cur) => { if (cur.completed){ pre++ } return pre },0)); //2