자바스크립트 문법(3) - 배열

윤보라·2022년 8월 4일

자바스크립트

목록 보기
3/11

[ 1. 배열의 선언 ]

// 1번째 방법
const arr1 = new Array(1, 2, 3, 4, 5)

// 2번째 방법
const arr2 = [1, 2, 3, 4, 5]  → 이 방법이 훨씬 간단하고 많이 씀!

[ 2. 배열 안의 데이터 ]

데이터의 인덱스는 0부터 시작된다는 점 유의하기!

(예시)

const family = ['bora','ddooby']

console.log(family[0])     → bora
console.log(family[1])     → ddooby


1) 데이터의 길이

console.log(family.length)2

// length 를 응용하여 아래와 같이 배열의 마지막 요소도 쉽게 찾아서 출력 가능

console.log(family[family.length - 1]) 


2) 데이터 추가(push)/삭제(pop)

family.push('SG')  → 배열의 마지막에 SG를 추가

family.pop()→ 배열의 마지막 요소 SG를 제거

[ 3. 배열과 반복문 ]

(기본예시)

const number = ['num1','num2','num3','num4','num5']

for (let i = 0; i < number.length; i++) {
	console.log(number[i])
}

→ 결과
num1
num2
num3
num4
num5
[훨씬 자주 쓰이는 더 간결한 for!!]

const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

for (const color of rainbowColors) {
	console.log(color)
}
profile
Front-End 개발자

0개의 댓글