자바스크립트 기본 내용은 많이 숙지한 상태라 반복문, 조건문까지는 무난히 따라감. class, 객체 쪽에서 생소한 문법이 있어서 정리하고 넘어가고자 함.
class Notebook {
constructor(name, price, company) {
this.name = name
this.price = price
this.company = company
}
}
객체가 생성될 때 JS 내부에서 호출되는 함수라고 생각하기
객체 자신 의미. 뒤에는 속성(name, price, company)
전에 this가 이해되지 않았는데 이번 기회에 this가 무엇인지 이해하게 됨
const notebook1 = new Notebook('MacBook', 2000000, 'Apple')
console.log(notebook) // Notebook { name: 'Macbook', price: 2000000, company: 'Apple' }
console.log(notebook.name) // MacBook
consoel.log(notebook.price) // 2000000
console.log(notebokk.company) // Apple
// 클래스 선언
class Product {
constructor(name, price) {
this.name = name
this.price = price
}
printInfo() {
console.log(`상품명: ${this.name}, 가격: ${this.price}원`)
}
}
// 객체 생성 및 메소드 호출
const notebook = new Product('Apple Macbook', 2000000)
notebook.printInfo() // 상품명: Apple Macbook, 가격: 2000000원
const computer = {
name: 'Apple Macbook',
price: 20000,
printInfo: function () {
console.log(`상품명: ${this.name}, 가격: ${this.price}원`)
}
}
computer.printInfo()
문제 : 배열을 만들고 합계와 평균 구하기
const price = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
let sum = 0
count = price.length
for (let i = 0; i < price.length; i++) {
sum += price[i]
}
console.log(sum)
console.log(sum / count)
const priceList = [1000, 2000, 5000, 7000, 10000, 9000, 3000, 15000, 20000, 17000]
let sum = 0
for (const price of priceList) {
sum += price
}
const avg = sum / priceList.length
console.log(`합계: ${sum}, 평균: ${avg}`)