JS计算购物车中商品总价,供大家参考,具体内容如下
题目要求:
购物车中有若干商品信息,其中包括商品的名称、单价、数量,计算购物车中商品的总价。
具体思路:
商品信息通过创建商品对象来实现,若干商品的加和通过创建数组来放置若干商品,再通过遍历数组读取指定属性对价格进行计算。
具体代码:
- <script type="text/javascript">
- // 总价变量
- var sum = 0;
- // 商品对象
- function Goods(name,price,amount){
- this.name = name;
- this.price = price;
- this.amount = amount;
- // this.add = fun();
- }
- // 定义声明商品实例
- var goods1 = new Goods("钢笔",100,1);
- var goods2 = new Goods("纸巾",10,1);
- var goods3 = new Goods("练习册",100,2);
-
- // 创建函数进行总价计算
- function totalPrice(){
- // 将对象放入数组
- var arr = new Array(goods1,goods2,goods3);
- // 通过遍历将各个商品价格进行相加
- for(var i in arr){
- sum = sum + (arr[i].price * arr[i].amount);
- };
- console.log(sum);
- };
-
- console.log(goods1);
- console.log(goods2);
- console.log(goods3);
- totalPrice();
- </script>
运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。