오늘 새롭게 태어났다...!
진짜진짜 시작이란 마음으로 수업을 열심히 들었다.
근데 약간 진짜 약간 졸았다 ㅎ
자바스크립트 문법강의
let과 const
let은 변수를 지정하고 값을 할당한다 - 재할당 가능!
const는 변수에 값을 재할당할 필요가 없을 때 값 고정!const priceList = [1000, 2000, 5000, 7000, 10000, 9000, 3000, 15000, 20000, 17000] let sum = 0 for (const price of priceList) { sum += price } // 재할당 할 때는 let 다시 쓰지 않는다! // += 대입연산자! 더하면서 대입한다 (=누적값) const avg = sum / priceList.length console.log(`합계: ${sum}, 평균: ${avg}`)
템플릿 리터럴 (Template literals)
백틱 사이에 써주면 문자열을 편리하게 붙여 쓸 수 있음!const shoesPrice = 200000 console.log(`이 신발의 가격은 ${shoesPrice}원입니다`) // console.log('이 신발의 가격은 ' + shoesPrice + '원입니다') 와 동일
console.log(10 2) 는 10의 제곱
console.log(10 3)은 10의 세제곱
증감연산자 (Increment and Decrement operators)
let count = 1 const preIncrement = ++count //count에 먼저 더하고 preIncrement에 저장해서 둘의 값이 동일 let count = 1 const postIncrement = count++ //postIncrement에 증감되기 전 count값이 들어가기 때문에 새로 증감된 count값은 적용되지 않는다
논리연산자: || (or), && (and), ! (not)
일치연산자: ===
(==은 자료형을 구분짓지 않아서 정확하지 않다!)
반복문을 만들 때 끝나지 않는 무한루프에 빠져서 프로그램의 실행이 끝나지 않는다면 터미널에 ctrl + c 를 눌러서 중단!
함수
function calculateAvg(price1, price2) { const sum = price1 + price2 console.log(`두 상품의 가격 총합은 ${sum}입니다.`) const avg = sum / 2 return avg } const price3 = 3000 const price4 = 1000 const avg1 = calculateAvg(price3, price4) console.log(`3,4의 평균은 ${avg1}입니다.`) // parameter: 매개변수. 여기선 price1, price2. // 새로운 값 price3,4의 값을 함수의 매개변수에 대입만 시켜주면 됨!
객체
클래스를 미리 정의해놓으면 필요할 때마다 그 클래스를 사용해서 동일한 모양을 가진 객체를 만들 수 있다!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() // this: 클래스를 사용해 만들어질 객체 자기 자신을 의미 // this 뒤에 붙는 name, price, company는 객체의 속성 // 객체 생성 및 메소드 호출하기! // 상품명: Apple Macbook, 가격: 2000000원
클래스보다 간단하게 하고싶다면 객체 리터럴(Object Literal)
const computer = { name: 'Apple Macbook', price: 20000, printInfo: function () { console.log(`상품명: ${this.name}, 가격: ${this.price}원`) } } computer.printInfo()
배열
const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] console.log(rainbowColors.length) // 7을 출력함.(0~6) console.log(rainbowColors[rainbowColors.length - 1]) // length-1은 배열의 마지막 요소! 0부터 시작하니까~! rainbowColors.push('ultraviolet') // 배열의 마지막에 ultarviolet 추가 rainbowColors.pop() // 배열의 마지막 요소 ultraviolet을 제거 - pop()은 뭘 해도 그냥 마지막 값만 없애줌!
다른 예시
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}`)
// priceList에서 요소들을 차례대로 하나씩 찾아 price라는 변수에 할당! length알 필요 없이 자동으로 배열의 끝까지 반복문이 실행되기 때문에 편함