<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>reduce方法</title>
</head>
<body>
<script>
/**
* 场景1
* 计算数组中所有值的总和
*/
var numbers = [10,20,30];
var sum = 0;
// es5
for(var i=0;i<numbers.length;i++){
sum += numbers[i];
}
console.log(sum);
// es6 reduce
var sumValue = numbers.reduce((sum,number) =>{
return sum + number;
},0); // 0为初始值
console.log(sumValue);
/**
* 场景2
* 将数组中对象的某个属性抽离到另外一个数组中
*/
var primaryColors = [
{color:"red"},
{color:"yellow"},
{color:"blue"}
]
var colors = primaryColors.reduce((previous,primaryColor) => {
previous.push(primaryColor.color);
return previous;
},[]);
console.log(colors);
/**
* 场景3
* 判断字符串中括号是否对称
*/
function balanceParents (string) {
return !string.split("").reduce((previous,char) =>{
if(char == "("){return ++ previous;}
if(char == ")"){return -- previous;}
},0);
}
// true 代表对称 false代表不对称
console.log(balanceParents("((())"));
</script>
</body>
</html>
es6 reduce方法
最新推荐文章于 2024-09-03 11:07:48 发布