javaScript中的reduce方法;统计字符串出现频率;求最大值;将字符串数字转换成整数

reduce()方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值

1、求数组累加和

// 数组求和
let arr = [1,2,3,4]
let res = arr.reduce((pre,cur) => {
    return pre + cur
},0)
console.log(res)

2、reduce统计字符串出现频率

        第一种方法

const arr = ["b", "c", "b", "c", "a", "b", "c"]
const obj = arr.reduce((allNum,num) => {
    if(num in allNum) {
        allNum[num]++
    }else {
        allNum[num] = 1
    }
    return allNum
},{})
console.log(obj)

         第二种方法

const str = 'hhkdaxnkhincwhiweeiuxcbjh'
// 将字符串转成数组
const arr = str.split('')
const map = {}

arr.reduce((prev,e) => {
    return map[e] = (map[e] || 0)  + 1
})

console.log(map)

         第三种方法

const str = 'aksdkabkascnsdkvbjhsbjshbjbcjs'
const arr = str.split('')
const map = {}
for (const k of arr) {
     map[k] = (map[k] || 0) + 1
}
console.log(map)

3、求最大值

let arr = [123,234,345,546,12,234]
let max = arr.reduce((pre,cur) => {
    return pre > cur ? pre : cur
})
console.log(max)

4、reduce将字符串数字转换成整数

let str = '4321'
console.log(str.split('').map(item => {return item.charCodeAt()})) // 得到一个字符串数组 ['4', '3', '2', '1']
let newStr = str.split('')
let newNewStr = newStr.map(item => {return item.charCodeAt() - 48}) // 得到 [52, 51, 50, 49]  -48后得到 [4, 3, 2, 1]
//charCodeAt() 方法可返回指定位置的字符的 Unicode 编码,返回值是 0 - 65535 之间的整数
let res =  newNewStr.reduce((a,b) => {
    return a * 10 + b
})
console.log(res) // 得到4321 整数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值