27.1 배열이란?

  • 배열(array) : 여러 개의 값을 순차적으로 나열한 자료구조
  • 요소(element) : 배열이 갖고 있는 값
  • 인덱스(index) : 배열에서 요소의 위치
  • 일반객체와 다르게 배열은 값의 순서와 length 프로퍼티가 있다.
const arr = ['apple', 'banana', 'orange'];

console.log(arr[0]);	// 'apple'
console.log(arr[1]);	// 'banana'
console.log(arr[2]);	// 'orange'
// length 프로퍼티 -> 배열 길이
console.log(arr.length);	// 3

// 값의 순서가 있기 때문에 배열의 순회 가능
for(int i = 0; i < arr.length; i++) {
  console.log(arr[i]);	// 'apple'\n'banana'\n'orange'
}
const arr = [1, 2, 3];

console.log(typeof arr);	// object → 배열은 객체다
// 생성자 함수 Array
console.log(arr.constructor === Array);	// true
// 프로토타입 객체 Array.prototype → 빌트인 메서드 제공
console.log(Object.getPrototypeOf(arr) === Array.prototype);	// true

27.2 자바스크립트 배열은 배열이 아니다

일반적 의미의 배열(밀집 배열, dense array)은 동일한 크기의 메모리 공간이 연속으로 나열된 자료구조를 말한다.

자바스크립트의 배열(희소 배열, sparse array)은 각 요소의 메모리 공간이 동일하지 않아도 되고 연속적이지 않을 수 있다.

즉, 자바스크립트의 배열은 일반적인 배열의 동작을 흉내낸 특수한 객체다.

27.3 length 프로퍼티와 희소 배열

  • length 프로퍼티 값은 0~2^32-1(4,294,967,296-1) 사이의 양의 정수값을 갖는ㄴ다. 즉 최개 2^32-2개의 요소를 가질 수 있다.
const arr = [1, 2, 3];

// 배열 요소 추가/삭제시 length 프로퍼티값은 자동 갱신
console.log(arr.length);	// 3
// 맨 뒤에 요소 추가
arr.push(4);
console.log(arr.length);	// 4
// 마지막 요소 삭제
arr.pop();
console.log(arr.length);	// 3

// 현재 legnth 프로퍼티 값보다 작은값 할당하면 배열 길이가 줄어든다.
arr.length = 2;
console.log(arr);	// [ 1, 2 ]
// 큰 값 할당하면 배열 길이 늘어나지 않는다.
arr.length = 3;
console.log(arr);	// [ 1, 2, <1 empty item> ]
console.log(Object.getOwnPropertyDescriptors(arr));
// {
//    '0': { value: 1, writable: true, enumerable: true, configurable: true },
//    '1': { value: 2, writable: true, enumerable: true, configurable: true },
//    length: { value: 3, writable: true, enumerable: false, configurable: false }
// }
  • 희소 배열은 length 프로퍼티 값이 실제 요소 개수보다 항상 크다. 문법적으로는 허용되지만 사용하지 않는 것이 좋다.
const sparse = [ , 2, , 4];

console.log(sparse.length);	// 4
console.log(sparse);	// [ <1 empty item>, 2, <1 empty item>, 4 ]
console.log(Object.getOwnPropertyDescriptors(sparse));
// {
//    '1': { value: 2, writable: true, enumerable: true, configurable: true },
//    '3': { value: 4, writable: true, enumerable: true, configurable: true },
//    length: { value: 4, writable: true, enumerable: false, configurable: false }
// }
  • 배열에는 값은 타입의 요소를 연속적으로 위치시키는 것이 최선이다.

27.4 배열 생성

// 배열 리터럴
const arr = [1, 2, 3];
const arrEmpty = [];
const arrSparse = [1, , 3];

// Arrat 생성자 함수
const arr2 = new Array(10);	// length가 10인 희소 배열 생성
new Array();	// [] 빈 배열 생성
Array(1, 2, 3);	// [ 1, 2, 3 ]	new 연산자 생략 가능
// Array.of 전달된 인수를 요소로 갖는 배열 생성
Array.of(1, 2, 3);	// [ 1, 2, 3 ]
Array.of('string');	// [ 'string' ]

// Array.from 유사 배열 객체 또는 이터러블 객체를 인수로 전달받아 배열로 변환
Array.from('Hello');	// [ 'H', 'e', 'l', 'l', 'o' ]
Array.from({ length: 2, 0: 'a', 1: 'b' });	// [ 'a', 'b' ]
Array.from({ length: 2 });	// [ undefined, undefined ] → length만 있으면 undefined로 값 넣음
Array.from({ length: 3 }, (_, i) => i);	// [ 0, 1, 2 ] → 두번째 인수로 전달한 콜백 함수의 반환값으로 배열 구성

27.5~7 배열 요소의 참조/추가와 갱신/삭제

  • 배열의 요소 참조
const arr = [1, 2, 3];
console.log(arr[0]);	// 1
console.log(arr[3]);	// undefined

const sparse = [, 2];
console.log(sparse[0]);	// undefined
  • 배열 요소의 추가와 갱신
  • 배열 요소의 삭제

이웅모 저자의 <모던 자바스크립트 Deep Dive> 책으로 스터디 하면서 공부한 내용들을 요약 정리해서 올리는 글입니다. 더 자세한 내용이 궁금하신 분들은 책을 봐주세요.

0개의 댓글