Skip to content

Instantly share code, notes, and snippets.

@lushijie
Last active February 18, 2016 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lushijie/f80421a5e5991fadd954 to your computer and use it in GitHub Desktop.
Save lushijie/f80421a5e5991fadd954 to your computer and use it in GitHub Desktop.
数组reduce方法
//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