์๊ตฌ์ฌํญ
- ๋ฐ์ดํฐ ์ ์ (JS):
- ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง ์ํ ๊ฐ์ฒด ๋ฐฐ์ด์ JavaScript ์ฝ๋ ๋ด์ ์ ์ํฉ๋๋ค. ์ด ๋ฐฐ์ด์ cartItems ๋ณ์์ ์ ์ฅํ์ธ์.
-
JavaScript
const cartItems = [ { id: 1, name: '๋ ธํธ๋ถ', price: 1200000, quantity: 1 }, { id: 2, name: '๋ฌด์ ๋ง์ฐ์ค', price: 35000, quantity: 2 }, { id: 3, name: '๋ชจ๋ํฐ', price: 300000, quantity: 1 }, { id: 4, name: 'ํค๋ณด๋', price: 80000, quantity: 3 } ];
- ์ดํฉ ๊ณ์ฐ ํจ์ ๊ตฌํ:
- calculateTotal์ด๋ผ๋ ํจ์๋ฅผ ๊ตฌํํฉ๋๋ค.
- ์ด ํจ์๋ cartItems ๋ฐฐ์ด์ ์ธ์๋ก ๋ฐ์์ผ ํฉ๋๋ค.
- ํจ์๋ ๋ฐฐ์ด์ ์ํํ๋ฉฐ **๊ฐ ์ํ์ ๊ธ์ก (price * quantity)**์ ๊ณ์ฐํ๊ณ , ์ด ๊ธ์ก๋ค์ ๋ชจ๋ ๋ํ ์ต์ข ํฉ๊ณ ๊ธ์ก์ ๋ฐํํด์ผ ํฉ๋๋ค. (ํํธ: Array.prototype.reduce() ์ฌ์ฉ์ ๊ถ์ฅํฉ๋๋ค.)
- ์ด ๊ฐ์ ๊ณ์ฐ ํจ์ ๊ตฌํ:
- calculateTotalQuantity๋ผ๋ ํจ์๋ฅผ ๊ตฌํํฉ๋๋ค.
- ์ด ํจ์๋ ๋ฐฐ์ด์ ์ํํ๋ฉฐ ๋ชจ๋ ์ํ์ quantity๋ฅผ ๋ํ ์ด ๊ฐ์๋ฅผ ๋ฐํํด์ผ ํฉ๋๋ค.
- HTML ๋ฐ ์ถ๋ ฅ:
- <body> ์์ <h2>์ <div id="result">๋ฅผ ๋ง๋ญ๋๋ค.
- JavaScript๋ฅผ ์ฌ์ฉํ์ฌ ๋ ํจ์๋ฅผ ์คํํ๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ result ์์ ์์ ์ถ๋ ฅํฉ๋๋ค.
- ์: "์ด ์ํ ๊ธ์ก: 1,695,000์ (์ด ์๋: 7๊ฐ)"
๋๋ณด๊ธฐ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>๋ฐฐ์ด ๋ฐ ํจ์๋ฅผ ํ์ฉํ ์ฅ๋ฐ๊ตฌ๋ ๊ณ์ฐ๊ธฐ</h2>
<div id="result"></div>
<script>
const cartItems = [
{id: 1, name: '๋
ธํธ๋ถ', price: 1200000, quantity: 1},
{id: 2, name: '๋ฌด์ ๋ง์ฐ์ค', price: 35000, quantity: 2},
{id: 3, name: '๋ชจ๋ํฐ', price: 300000, quantity: 1},
{id: 4, name: 'ํค๋ณด๋', price: 80000, quantity: 3},
{id: 5, name: '๋ง์ฐ์ค ํจ๋', price: 10000, quantity: 2},
];
document.addEventListener("DOMContentLoaded", () => {
const resultElement = document.getElementById('result');
function calculateTotal(items) {
const total = items.reduce((accumulator, item) => {
const itemTotal = item.price * item.quantity;
return accumulator + itemTotal;
}, 0);
return total;
}
function calculateTotalQuantity(items) {
const totalQuantity = items.reduce((accumulator, item) => {
return accumulator + item.quantity;
}, 0);
return totalQuantity;
}
const finalTotal = calculateTotal(cartItems);
const finalQuantity = calculateTotalQuantity(cartItems);
const formattedTotal = finalTotal.toLocaleString('ko-KR');
const resultText = `์ด ์ํ ๊ธ์ก : ${formattedTotal}์ (์ด ์๋ : ${finalQuantity}๊ฐ)`;
resultElement.textContent = resultText;
})
</script>
</body>
</html>
