Class: 제로베이스
Created: December 2, 2022 11:38 AM
Type: Javascript
강의 명: 이론부터 실전까지 모든 것을 담은 자료구조/알고리즘
배열 안에 N개 만큼의 배열이 존재하는 객체
2 / 3 차원 지도 정보, RBG 를 저장하는 2차원 사진 파일 등을 표현할 떄 활용 가능하다.
2차원 배열은 array[N][M] 으로 접근 가능하며, 배열(Array) 전체를 push( ), pop( ) 가능함
let array = [
[101, 102, 103],
[201, 202, 203],
[301, 302, 303],
[401, 402, 403],
];
console.log(array);
// [ [ 101, 102, 103 ], [ 201, 202, 203 ], [ 301, 302, 303 ], [ 401, 402, 403 ] ]
/* length로 2차원 배열의 크기 구하기 */
console.log(array.length); // 4
console.log(array[0].length); // 3
/* 각 요소에 접근 */
console.log(array[0]); // [ 101, 102, 103 ]
console.log(array[0][0]); // 101
/* 행 전체 삭제 */
let popped_element = array.pop(); // 삭제하고 popped_element에 저장
console.log(array); // [ [ 101, 102, 103 ], [ 201, 202, 203 ], [ 301, 302, 303 ] ]
console.log(array.length); // 3
console.log(popped_element); // [ 401, 402, 403 ]
/* 요소 하나만 삭제하고 싶다면? */
let popped_element2 = array[0].pop(); // 삭제하고 popped_element2에 저장
console.log(array); // [ [ 101, 102 ], [ 201, 202, 203 ], [ 301, 302, 303 ] ]
console.log(popped_element2); // 103
/* 요소 추가 */
let array_num = array.push([501, 502, 503]); // 추가된 이후 행의 개수 저장
console.log(array); // [ [ 101, 102 ], [ 201, 202, 203 ], [ 301, 302, 303 ], [ 501, 502, 503 ] ]
console.log(array.length); // 4
console.log(array_num); // 4
이중 for loop를 사용한 2차원 배열 접근
let array = [
[101, 102, 103],
[201, 202, 203],
[301, 302, 303],
[401, 402, 403],
];
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
console.log(array[i][j]);
}
} // 101 102 103 201 202 203 301 302 303 401 402 403
let recipe = [
["strawberry", 50],
["banana", 100],
["ice", 150],
]; // 배열의 각 요소가 서로 다른 자료형을 가질 수 있다
for (let i = 0; i < recipe.length; i++) {
console.log(`fruit: ${recipe[i][0]}, amount: ${recipe[i][1]}`);
} // fruit: strawberry, amount: 50
// fruit: banana, amount: 100
// fruit: ice, amount: 150