Last active
February 18, 2016 02:18
-
-
Save lushijie/f80421a5e5991fadd954 to your computer and use it in GitHub Desktop.
数组reduce方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1.数组求和 | |
var arr = [1,2,3,4]; | |
var total = arr.reduce(function(pre, cur, index, arr){ | |
//接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce 的数组 | |
//arr.reduce(callback,[initialValue]) | |
return pre + cur; | |
}) | |
console.log(total) | |
//2.把二维数组转换为json键值对 | |
var relArray = [ | |
["Viola", "Orsino"], | |
["Orsino", "Olivia"], | |
["Olivia", "Cesario"] | |
]; | |
var relMap = relArray.reduce(function(memo, curr) { | |
memo[curr[0]] = curr[1]; | |
return memo; | |
}, {}); | |
console.log(relMap); | |
/*Outputs: | |
{ | |
"Viola": "Orsino", | |
"Orsino": "Olivia", | |
"Olivia": "Cesario" | |
}*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment