하위 태스크 1
scope.js 생성
전역/지역 스코프 실습 파일 생성
scope.js 파일을 생성한다.
New-Item -Path .\scope.js -ItemType File변수의 스코프를 알아보기 위한 예제를 작성한다. 예제에서 각 변수의 특징은 다음과 같다.
globalA: 전역 변수로 선언되었다. 함수, 반복문, 조건문 내에서 접근할 수 있다.localA: 함수foo내에 지역 변수로 선언되었다. 함수foo외부에서 사용할 수 없다.
scope.js:
var globalA = "global A";
function foo() {
var localA = "local A";
console.log(globalA, localA); // global A local A
}
foo();
// console.log(globalA, localA); // ReferenceError하위 태스크 2
전역/지역 변수 테스트
같은 이름의 변수를 전역·지역에 선언해 출력 비교
b: 전역 변수로 선언되었다.- 함수
foo내부의b: 함수bar내에 지역 변수로 선언되었다. 전역 변수b와 식별자가 같으므로 전역 변수b를 가린다(shadowing).
scope.js:
var b = "global B";
function bar() {
var b = "local B";
console.log(b); // local B
}
bar();
console.log(b); // global B하위 태스크 3
블록 스코프 테스트
if/for 블록 안 변수의 접근 범위 확인
varC:var키워드로 선언된 지역 변수다.var로 선언된 변수는 블록 스코프를 지원하지 않으므로 if 문 외부에서 접근할 수 있다.constC:const키워드로 선언된 지역 변수다.const로 선언된 변수는 블록 스코프를 지원하므로 if 문 외부에서 접근할 수 없다.letC:let키워드로 선언된 지역 변수다.let으로 선언된 변수는 블록 스코프를 지원하므로 if 문 외부에서 접근할 수 없다.
scope.js:
if (true) {
var varC = "var C";
const constC = "const C";
let letC = "let C";
}
console.log(varC); // var C
// console.log(constC, letC); // ReferenceError
for (var i = 0; i < 10; i += 1) {
var j = 0;
const k = 0;
let l = 0;
}
console.log(j); // 0
// console.log(k, l); // ReferenceError하위 태스크 4
user 객체 정의
사용자 정보를 담는 객체 생성 및 프로퍼티 조작
user.js 파일을 생성한다.
New-Item -Path .\user.js -ItemType Fileuser.js:
- 객체의 프로퍼티는 점 표기법(
.) 또는 대괄표 표기법([])으로 접근할 수 있다. - 존재하지 않는 객체의 프로퍼티에 값을 할당하면 프로퍼티가 추가된다.
- 객체의 프로퍼티와 함께
delete연산자를 사용하면 해당 프로퍼티를 삭제한다.
const user = {
name: "gildong",
age: 23,
email: "[email protected]",
address: "서울특별시 강남구",
};
console.log(user.name); // gildong
console.log(user["email"]); // [email protected]
user.job = "programmer"; // 프로퍼티 추가
user.age = 30; // 프로퍼티 수정
delete user.address; // 프로퍼티 삭제하위 태스크 5
프로퍼티 존재 여부 확인
in 연산자 또는 hasOwnProperty 로 체크
user.js:
for ... in문은 열거할 수 있는 객체의 프로퍼티 키를 순회한다.
// ... 하위 태스크 4
for (const key in user) {
console.log(`${key}: ${user[key]}`);
// name: gildong
// age: 30
// email: [email protected]
// job: programmer
}하위 태스크 6
객체 메서드 추가
사용자 정보 출력 메서드 구현
scope.js:
// ... 하위 태스크 5
user.say = function () {
console.log(`저는 ${this.age}살 ${this.name}입니다.`);
};
user.say(); // 저는 30살 gildong입니다.하위 태스크 7
cartItems 배열 정의
장바구니 아이템 배열 생성(객체 3개 이상)
cart.js:
const cartItems = [
{ name: "potato", price: 1000, quantity: 3 },
{ name: "egg", price: 500, quantity: 8 },
{ name: "tomato", price: 600, quantity: 3 },
];하위 태스크 8
총 금액 계산
반복문으로 (price * quantity) 합계 계산
cart.js:
// ... 하위 태스크 7
let sum = 0;
for (let i = 0; i < cartItems.length; i += 1) {
const item = cartItems[i];
sum += item.price * item.quantity;
}
console.log(sum); // 8800하위 태스크 9
아이템 추가/삭제/수정
배열 조작으로 장바구니 변경 로직 구현
cart.js:
// ... 하위 태스크 8
function setQuantity(quantity, name) {
for (const key in cartItems) {
if (cartItems[key].name !== name) {
continue;
}
cartItems[key].quantity = quantity;
}
}
function deleteItem(name) {
for (const key in cartItems) {
if (cartItems[key].name !== name) {
continue;
}
delete cartItems[key];
}
}
setQuantity(10, "egg");
deleteItem("tomato");
console.log(cartItems);
/*
[
{ name: 'potato', price: 1000, quantity: 3 },
{ name: 'egg', price: 500, quantity: 10 }
]
*/하위 태스크 10
배열 메서드 활용
push, pop, splice 등으로 배열 조작
cart.js:
// ... 하위 태스크 9
cartItems.push({ name: "banana", price: 3000, quantity: 2 });
const lastItem = cartItems.pop();
cartItems.splice(1, 1);
console.log(lastItem); // { name: 'banana', price: 3000, quantity: 2 }
console.log(cartItems); // [ { name: 'potato', price: 1000, quantity: 3 } ]