習作3 - 完成答案版

HTML, CSS, JS | 前端網站開發課程

問題 1:HTML & CSS

✓ 1a 答案

CSS 代碼:

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.product {
  border: 1px solid #ddd;
  padding: 16px;
  border-radius: 8px;
  background-color: #f9f9f9;
}

說明: 使用 CSS Grid 創建 3 列的網格佈局,每個產品卡片具有邊框、內距和圓角。

✓ 1b 答案

.product img {
  width: 100%;
  height: auto;
}

說明: 設置圖片寬度為容器的 100%,高度自動調整以保持寬高比,實現響應式設計。

問題 2:JavaScript

✓ 2a 答案

let total = 0;
for (let i = 0; i < products.length; i++) {
  total += products[i].price * products[i].quantity;
}
console.log(total);  // 1635

或使用 reduce():

let total = products.reduce((sum, p) => sum + (p.price * p.quantity), 0);

✓ 2b 答案

let maxPrice = Math.max(...products.map(p => p.price));
let maxProduct = products.find(p => p.price === maxPrice);
console.log(maxProduct.name);  // "草莓起司蛋糕"

或使用 reduce():

let maxProduct = products.reduce((max, p) => p.price > max.price ? p : max);
console.log(maxProduct.name);

✓ 2c 答案

function findProductPrice(products, name) {
  for (let i = 0; i < products.length; i++) {
    if (products[i].name === name) {
      return products[i].price;
    }
  }
  return null;
}

// 調用
console.log(findProductPrice(products, "巧克力蛋糕"));  // 45

或使用 find():

let product = products.find(p => p.name === name);
return product ? product.price : null;