reduce的用法技巧(代码示例)


本文摘自PHP中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于reduce的用法技巧(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

reduce

数组的方法,有两个参数 回调函数callback 和 initialValue
回调有四个参数 prev、next、index、arr
initialValue:可选参数,作为callback第一次的prev;
如果传了initialValue:
prev第一次为initialValue,之后为return的值。
next为数组的每一项
index为数组的下标
arr为原数组
如果没传initialValue:
prev第一次为数组的第一项,之后为return的值。
next为从数组的第二项开始的每一项
index、arr不受影响

下划线转驼峰

1

2

3

4

5

6

7

8

let str = "my_name_is_sxq";

let result = str.split('').reduce((p,n,i,arr)=>{

    if(n=='_'){

        arr[i+1] = arr[i+1].toUpperCase()

        return p

    }

    return p + n

})

数组扁平化

1

2

3

4

5

// 二维转一维

let arr = [1,2,3,[4,5],[6,7,[8,9]]];

let newarr = arr.reduce(function(prev,next){

    return Array.isArray(next)?prev=prev.concat(...next):prev=prev.concat(next)

},[])

数组转对象

1

2

3

4

5

6

// 路由数组转对象

let arr = [{path:'/',component:function(){}},{path:'/user',component:function(){}}]

let result = arr.reduce((memo,current)=>{

    memo[current.path] = current.component

    return memo

},{})

以上就是reduce的用法技巧(代码示例)的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

关于javascript监听组合按键

javascript如何实现异步

javascript如何实现加减乘除

javascript中怎么换行

详解javascript中的padstart()和padend()方法

了解javascript中3种for循环风格以及何时使用它们

如何使用js.map()方法(数组方法)

javascript怎么设置全选

javascript中什么是set?什么时候使用?如何使用?

javascript怎么执行cmd命令

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...