채린씨의 티스토리
29. Array 본문
* 배열
- 여러 개체(Entity) 값을 순차적으로 나열한 자료 구조 (알고리즘 내 사용 빈도 많음)
- 배열 내 값을 요소(element)라고 하며, 배열 요소는 index로 접근
* 배열 선언 / 접근 / 속성
- 배열 선언: new Array() 혹은 []를 이용해 선언하며, 사이즈나 값을 입력하여 초기화도 가능
- 배열 접근: Array[index]를 이용해 O(1)의 시간 복잡도로 접근 가능(매우 빠름)
- 배열 속성: Array.length를 이용해 배열 요소의 개수 확인 가능
* 배열의 실체
- JavaScript에서 배열은 다른 언어에서 말하는 일반적인 배열이 아닌 Hash 기반의 객체
- 메모리가 연속적인 밀집 배열(dense array)이 아닌 비연속적인 희소 배열(sparse array)
let nums = [];
nums.push("one"); // 배열 nums에 "one" 추가
nums.push("two"); // 배열 nums에 "two" 추가
console.log(nums.length); // output: 2 (배열 nums의 원소의 개수)
console.log(nums); // output: [ 'one', 'two' ]
console.log(Object.getOwnPropertyDescriptors(nums));
/* output:
{ '0': { value: 'one', writable: true, enumerable: true, configurable: true },
'1': { value: 'two', writable: true, enumerable: true, configurable: true },
length: { value: 2, writable: true, enumerable: false, configurable: false }
}
push를 이용해 개체를 추가하면, 자동으로 0부터 순서대로 커지는 정수값(인덱스)이 해당 개체를 가리킨다.
*/
// "length"도 하나의 인덱스처럼 저장되어 있는 것을 알 수 있다!!!
console.log(nums["length"]); // output: 2
// 문자열이 인덱스가 될 수도 있다?!?!?!
nums["once"] = "once";
nums["twice"] = "twice";
console.log(nums.length); // output: 2!!! (배열 nums의 원소의 개수)
console.log(nums); // output:[ 'one', 'two', once: 'once', twice: 'twice' ]
console.log(nums[2]); // output: undefined(인덱스 2가 가리키는 곳에는 아무것도 없음)
console.log(Object.getOwnPropertyDescriptors(nums));
/* output:
{ '0': { value: 'one', writable: true, enumerable: true, configurable: true },
'1': { value: 'two', writable: true, enumerable: true, configurable: true },
length: { value: 2, writable: true, enumerable: false, configurable: false },
once: { value: 'once', writable: true, enumerable: true, configurable: true },
twice: { value: 'twice', writable: true, enumerable: true, configurable: true }
}
문자열을 인덱스로 개체를 추가하면, 해당 개체들은 배열의 길이에 영향을 주지 않는다.
다만 일반 오브젝트의 key, value 관계처럼 nums["once"]로 해당 개체에 접근은 가능하다!
*/
- 아니, 문자열이 인덱스가 될 수 있다고?? 이해가 안되어요.. 내 배열 세상이 무너졌어.. 어쩌구 저쩌구..
https://okky.kr/article/871054
- javaScript에서는 배열이 단지 숫자로 된 키값들을 특별히 인덱스로 취급하는 일종의 '오브젝트'에 불과하다고 한다! o0o 댑악..
=> 결론: JavaScript에서의 배열은 key값으로 각 객체에 접근하는 hash 기반의 객체(오브젝트)!
따라서 메모리가 연속적이지 않고(희소 배열), 서로 다른 자료형의 객체도 저장할 수 있음!
* 배열 타입 확인
- 배열 타입 확인 방법: Array.isArray(value)
let num = 123.456;
let str = "Hi, I'm string!";
let fruits = ["apple", "orange", "melon"];
console.log(Array.isArray(num)); // output: false (num은 배열이 아니라 Number)
console.log(Array.isArray(str)); // output: false (str은 배열이 아니라 String)
console.log(Array.isArray(fruits)); // output: ture
* 배열 요소 삭제
- 배열 일부 요소 삭제: delete array[index] (삭제해도 배열 사이즈가 그대로)
let fruits = ["apple", "orange", "melon"];
console.log(fruits); // output: [ 'apple', 'orange', 'melon' ]
console.log(fruits.length); // output: 3
delete fruits[1]; // 인덱스 1이 가리키는 개체("orange") 삭제
console.log(fruits); // output: [ 'apple', <1 empty item>, 'melon' ]
console.log(fruits.length); // output: 3 (원소를 삭제해도 배열 사이즈는 그대로1!!)
이 방식으로 배열의 요소를 삭제하면, 배열 사이즈는 그대로이다. 이럴 경우, for문으로 배열의 각 요소에 접근하거나 할 때 원하지 않는 결괏값이 나올 수 있다. 이런 문제 없이 배열의 요소를 삭제하는 방법은 다음 시간에 알아보자!
'자료구조, 알고리즘 > JavaScript 기초 문법' 카테고리의 다른 글
31. 배열 탐색 - 변형 (0) | 2022.03.12 |
---|---|
30. 배열 조작(!) (0) | 2022.03.12 |
28. 문자열 변환 (0) | 2022.03.07 |
27. String (0) | 2022.03.07 |
26. Number (0) | 2022.03.07 |