JS計算購物車中商品總價,供大家參考,具體內容如下
題目要求:
購物車中有若干商品信息,其中包括商品的名稱、單價、數量,計算購物車中商品的總價。
具體思路:
商品信息通過創建商品對象來實現,若干商品的加和通過創建數組來放置若干商品,再通過遍歷數組讀取指定屬性對價格進行計算。
具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<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> |
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_46700766/article/details/114453834