ES6的reduce用法

1. 求和数组(基本用法)

let list = '12345'.split('')
const total = list.reduce((val, oldVal) => val + oldVal)
console..log(total) // 15

2. 去重数组

let list = '123123'.split('')
const newList = list.reduce((pre, cur) => {
    return pre.includes(cur) ? pre : pre.concat(cur)
}, [])
console.log(newList) // [1, 2, 3]

3. 求和数组中的对象

const list = []
for (let i = 0 ; i < 5 ; i++) {
    list.push({
        val: i + 1
    })
}
const newList = list.reduce((pre, cur) => {
    return pre + cur.val
}, 0)

console.log(newList) // 15

4. 计算数组中字符出现的次数

const list = 'abcabcabc'.split('')
const pre = list.reduce((pre, cur) => {
    if (pre[cur]) {
        pre[cur]++
    } else {
        pre[cur] = 1
    }
    return pre
}, {})
console.log(pre) // {a:3,b:3,c:3}

 

你可能感兴趣的:(原生JS,JS,es6,javascript)