解析javascript中的reduce函数
1 语法
arr.reduce(function(perviousValue, currentValue,[currentIndex],[arr]){
//业务逻辑
return undefined;
},[initialValue])
//其中arr为数组引用
//[currentIndex],[arr]、[initialValue]都是可选的,其余的参数都是必选的
//当有了initialValue,时,第一次时,previousValue=initialValue,currentValue=arr[0]
//若没有initialValue时,第一次时,previousValue=arr[0],currentValue=arr[1]
//函数的每次返回值都会赋值给perviousValue,让其开启下一次旅程
2 使用场景
用于对象数组中的累加操作
3 典型题目
3.1 题目内容
//~~删除线格式~~ 题目内容:统计一下json数据的商品总价
var goods = [{name:'牙膏',price:12.5},{name:'巧克力',price:20.8},
{name:'剃须刀',price:99.9},{name:'毛巾',price:18.8},
{name:'苹果13',price:6999.8},{name:'麻辣王子',price:3.5},
{name:'怡宝',price:2.3},{name:'芙蓉王',price:23.0},
{name:'棒棒糖',price:0.5},{name:'口罩',price:1.2}];
3.2 题目解答
3.2.1 附上初始值(initialValue)
a 示例html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试reduce函数的用法</title>
</head>
<body>
<script>
var goods = [{name:'牙膏',price:12.5},{name:'巧克力',price:20.8},
{name:'剃须刀',price:99.9},{name:'毛巾',price:18.8},
{name:'苹果13',price:6999.8},{name:'麻辣王子',price:3.5},
{name:'怡宝',price:2.3},{name:'芙蓉王',price:23.0},
{name:'棒棒糖',price:0.5},{name:'口罩',price:1.2}];
var totalPrice=goods.reduce(function(sum,ele){
sum+=ele.price;
return sum;
},0)
console.log("商品总价为: "+totalPrice);
</script>
</body>
</html>
b 示例代码运行截图
3.2.2 不附上初始值
a 示例html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试reduce函数的用法</title>
</head>
<body>
<script>
var goods = [{name:'牙膏',price:12.5},{name:'巧克力',price:20.8},
{name:'剃须刀',price:99.9},{name:'毛巾',price:18.8},
{name:'苹果13',price:6999.8},{name:'麻辣王子',price:3.5},
{name:'怡宝',price:2.3},{name:'芙蓉王',price:23.0},
{name:'棒棒糖',price:0.5},{name:'口罩',price:1.2}];
var totalPrice=goods.reduce(function(sum,ele){
//比较的是内容
if(sum==goods[0]){
return sum.price+ele.price;
}
sum+=ele.price;
return sum;
})
console.log("不附初始值时的求解方法");
console.log("商品总价为: "+totalPrice);
</script>
</body>
</html>