[JS] 배열

KJA·2022년 6월 30일
0

배열

순서가 있는 컬렉션이 필요할 때 사용합니다.

배열 선언

사과, 오렌지, 배, 딸기 각각의 값을 요소(element) 라고 합니다.

const fruits = ['사과', '오렌지', '배', '딸기'];

배열 내 특정 요소를 얻고 싶다면 대괄호 안에 순서를 나타내는 숫자인 인덱스를 넣어주면 됩니다.

const fruits = ['사과', '오렌지', '배', '딸기'];
console.log(fruits[0]); // 사과
console.log(fruits[1]); // 오렌지
console.log(fruits[2]); // 배
console.log(fruits[3]); // 딸기

같은 방법으로 요소를 수정할 수 있습니다.

fruits[1] = '바나나'; // 배열이 ['사과', '바나나', '배', '딸기']로 바뀜

새로운 요소를 배열에 추가하는 것도 가능합니다.

fruits[4] = '메론'; // 배열이 ['사과', '바나나', '배', '딸기', '메론']로 바뀜

이차원 배열

const arrayOfArray = [[1, 2, 3], [4, 5]];
arrayOfArray[0]; // [1, 2, 3]

const a = 10;
const b = 20;
const variableArray = [a, b, 30];
variableArray[1]; // 20 (b의 값)

.length

length를 사용하면 배열에 담긴 요소가 몇 개인지 알아낼 수 있습니다. 빈 값도 유효한 값이기 때문에 요소 개수를 셀 때 포함됩니다.

const fruits = ['사과', '오렌지', '배', '딸기'];

console.log(fruits.length); // 4

const emptyValue = [null, undefined, false, '', NaN];

console.log(emptyValue.length); // 5

배열의 마지막 요소 찾기

const findLastElement = ['a', 'b', 'c', 'd', 'e'];

console.log(findLastElement[findLastElement.length - 1]); // e

배열 마지막에 요소 추가하기

const findLastElement = ['a', 'b', 'c', 'd', 'e'];
findLastElement[findLastElement.length] = 'f';
console.log(findLastElement); // ['a', 'b', 'c', 'd', 'e', 'f']

pop·push와 shift·unshift

는 순서가 있는 컬렉션을 저장하는 데 사용합니다. 큐를 사용하면 먼저 집어넣은 요소가 먼저 나오기 때문에 큐는 선입선출(First-In-First-Out, FIFO) 이라고 부릅니다.

스택은 '한쪽 끝'에 요소를 더하거나 뺄 수 있게 해주는 자료구조 입니다. 스택을 사용하면 가장 나중에 집어넣은 요소가 먼저 나옵니다. 이런 특징을 후입선출(Last-In-First-Out, LIFO)이라고 부릅니다.

배열 끝에 무언가를 해주는 메서드

pop
배열 끝 요소를 제거하고, 제거한 요소를 반환합니다.

const element = ['a', 'b', 'c', 'd', 'e'];
console.log(element.pop()); // e
console.log(element); // ['a', 'b', 'c', 'd']

push
배열 끝에 요소를 추가합니다.

const element = ['a', 'b', 'c', 'd'];
element.push('e');
console.log(element); // ['a', 'b', 'c', 'd', 'e']

findLastElement.push(...)findLastElement[findLastElement.length] 하는 것과 같은 효과를 보입니다.

배열 앞에 무언가를 해주는 메서드

shift
배열 앞 요소를 제거하고, 제거한 요소를 반환합니다.

const element = ['a', 'b', 'c', 'd', 'e'];
console.log(element.shift()); // a
console.log(element); // ['b', 'c', 'd', 'e']

unshift
배열 앞에 요소를 추가합니다.

const element = ['b', 'c', 'd', 'e'];
element.unshift('a');
console.log(element); // ['a', 'b', 'c', 'd', 'e']

pushunshift는 요소 여러 개를 한 번에 더해줄 수도 있습니다.

const element = ['c'];

element.push('e', 'f');
element.unshift('a', 'b');

console.log(element); // ['a', 'b', 'c', 'e', 'f']

const를 사용했는데 수정 가능한 이유는 뭔가요?

const는 새로운 값을 대입(=) 못한다고 기억하면 됩니다. const에 객체(배열, 함수, 객체 리터럴)가 대입된 경우 객체 내부의 속성이나 배열의 요소는 수정할 수 있습니다.

const element = ['a', 'b', 'c', 'd', 'e'];
element = ['f', 'g']; // 불가능
element[0] = 'h'; // 가능

반복문

배열은 값들을 나열한 것이기 때문에 반복문과 같이 사용하는 경우가 많습니다. while문이나 for문 모두 사용할 수 있습니다.

while문

const element = ['a', 'b', 'c', 'd', 'e'];
let i = 0;
while(i < element.length){
  console.log(element[i]);
  i++;
}
// a
// b
// c
// d
// e

문자열도 인덱스가 있기 때문에 아래 코드도 위와 동일하게 출력됩니다.

const element = 'abcde';
let i = 0;
while (i < element.length) {
    console.log(element[i]);
    i++;
}
// a
// b
// c
// d
// e

for문

const element = ['a', 'b', 'c', 'd', 'e'];
for (let i = 0; i < element.length; i++) {
    console.log(element[i]);
}
// a
// b
// c
// d
// e

0개의 댓글