//js代码如下 //先定义一个商品数组
let arr_fruit = [
{
id: ‘001’,
checked: true,
name: ‘苹果’,
price: 100,
num: 1,
},
{
id: ‘002’,
checked: false,
name: ‘香蕉’,
price: 100,
num: 1,
},
{
id: ‘003’,
checked: true,
name: ‘西瓜’,
price: 300,
num: 2,
},
{
id: ‘004’,
checked: true,
name: ‘榴莲’,
price: 200,
num: 1,
},
];
//封装一个计算出所有商品的价格的函数
function fun(arr_fruit) {
//1.先用filter方法过滤checked为true的商品出来,
//2.然后再用map方法计算每个商品*数量的价格,
//3.最后再用reduce方法把所有商品价格累加起来
let all_price1 = arr_fruit.filter(function (item) {
return item.checked;
}).map(function (val) {
return val.price * val.num;
}).reduce((prev, val) => {
return prev + val;
});
return all_price1
}
fun(arr_fruit)
console.log(‘商品的总价格为’ + ‘:’ + fun(arr_fruit) + ‘元’);
控制台输出为: 商品的总价格为:900元
封装一个传入数组,计算出所有商品的价格的函数
最新推荐文章于 2024-07-10 14:03:37 发布