スーパーの商品をオブジェクトで表した。(商品名、価格、賞味期限)
賞味期限から残りの日数を計算するようにした。
実行イメージ

ソースコード
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 | <! DOCTYPE html> < html lang = "ja" > < 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" > < script src = "main.js" ></ script > < title >スーパーの商品をオブジェクト化</ title > </ head > < body > < p >コンソールに表示しています...</ p > </ body > </ html > |
main.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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | // main.js window.addEventListener( "load" , ()=>{ // 商品配列(オブジェクトで設定) const products = [ { name: "トマト" , // 商品名 price: 389, // 価格 exp: "2022/06/25" , // 賞味期限 }, { name: "オトメメロン" , price: 1500, exp: "2022/06/29" , }, { name: "ザッキー" , price: 198, exp: "2022/12/10" , }, { name: "ソース焼きそば" , price: 128, exp: "2022/6/19" , } ]; // 商品を表示する for ( let product of products){ // 今日の日付を文字列化(20XX/XX/XX) const now = new Date(); const strToday = now.getFullYear() + "/" + (now.getMonth()+1) + "/" + now.getDate(); // Dateオブジェクトに直す(差分日数計算のため) const today = new Date(strToday); const expday = new Date(product.exp); // 賞味期限計算 let left = (expday - today) / 86400000; if (left < 0) left = "賞味期限切れ" ; else left = "あと" + left + "日" ; // 商品別表示 console.log(`${product.name} ${product.price}円`); console.log(`\t${left} 賞味期限 ${product.exp}`); } }); |
コメント