目標:合計金額を出したい。
現状:totalpriceが一回一回のループ処理で出ている。
自分が考えた対策法:空の配列を作ってそこに、ループ処理の結果を一つずつ入れていき、popメソッドで最後の値だけ取り出す。
しかし、そのやり方が分からなく、調べても出てこない為、質問させていただきました。
js
1'use strict'; 2 3$(function () { 4 5 const tops = [ 6 {name: `UクルーT`, price: 1000}, 7 {name: `ワッフルクルーT`, price: 1500}, 8 {name: `ドライカノコポロシャツ`, price: 1990}, 9 {name: `UオーバーサイズクルーT`, price: 1500}, 10 {name: `UグラフィックT`, price: 1500}, 11 {name: 'エアリズムT', price: 990} 12 13 ]; 14 // console.log(t[Math.floor(Math.random()*t.length)]); 15 // result.textContent = t[Math.floor(Math.random()*t.length)].name; 16 17 const bottoms = [ 18 {name: '感動パンツ', price: 3990}, 19 {name: 'ウルトラストレッチスキニージーンズ', price: 3990}, 20 {name: 'EZYアンクルパンツ', price: 2990}, 21 {name: 'チノハーフパンツ', price: 1990}, 22 ]; 23 24 $('#search').on('click', function() { 25 let money = $('.main-top__content--money').val(); 26 let style = $('.main-top__content--style').val(); 27 28 let totalprice = 0; 29 30 $('#result').empty(); 31 $('#totalPrice').empty(); 32 33 while (totalprice <= money) { 34 let nonce = Math.floor(Math.random()*tops.length); 35 let name = tops[nonce].name; 36 let price = tops[nonce].price; 37 38 totalprice += price; 39 40 if (totalprice > money) { 41 break 42 }; 43 44 // 空の配列を作ってtotalpriceの値をひとつずつ入れていき、pop()で最後の値をとろうとした 45 // let sum = []; 46 // sum.push(totalprice); 47 // console.log(sum); 48 // let last = sum.pop(); 49 50 $('#result').append("商品名"+ " "+ name + " " + price + "円" + "<br>"); 51 $('#totalPrice').append("合計金額"+ totalprice + "円"); 52 // append(); 要素の追加 53 //合計金額A円合計金額A+B円合計金額A+B+C円みたいになってしまう 54 } 55 56 }); 57 58}); 59コード
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/03 13:05
2019/06/04 11:42
2019/06/06 07:02