생성 방법
let arr = [1, 2, 3] ; let arr2 = new Array(1, 2, 3); //같은 기능을 수행한다. let arr3 = Array.from({length: 5}, () => 7); //임의의 크기 5를 갖는 배열 생성하여 7로 초기화. let arr4 = [[0,1,2,3], [4,5,6,7]] // 2차원 배열 생성 let arr5 = Array.from(Array(4), ()=> new Array(5)) // [4][5]의 2차원 배열을 생성
배열 익히기
let arr = [1, 2, 3]; arr.length = 8; //index 0~7까지로 만듦 arr[6] = 10; arr.push(3) //index 하나 증가하고 3으로 넣음. //배열 내부 [1, 2, 3, undefined, undefined, undefined, 10, undefined, 8] let arr2 = [34, 5]; arr2 = arr.concat(arr2); // 서로 합친 결과 반환 arr2.slice(2, 4); //index 2~(4-1)까지 가져온다. O(N) arr2.indexOf(4); //4값을 가지는 첫째 인덱스 반환
JS에서 연결 리스트를 구현할 일은 없지만, 개념을 이해하는 수준으로 알아본다.
// stack 사용 예제
let stack = [];
stack.push(1); //[1];
stack.push(2); //[1, 2];
stack.push(3); //[1, 2, 3];
stack.pop(); //[1, 2];
stack.push(4); //[1, 2, 4];
let lifo = stack.reverse(); //Last In First Out 을 위한 배열 뒤집기.
console.log(lifo);
// Queue 구현
class Queue{
constructor (){
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++; //tailIndex 증가
} // 데이터 삽입
dequeue() {
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
} //데이터 추출
peek(){
return this.items[this.headIndex];
}
getLength(){
return this.tailIndex - this.headIndex;
}
}
queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5); //1, 2, 3, 4, 5 headIndex: 0, tailInedx : 5
queue.dequeue(); //1 반환 headInedx : 1
queue.enqueue(6); // 2, 3, 4, 5, 6 headInedx:1, tailInedx: 6
while (queue.getLength() != 0)
{
console.log(queue.dequeue())
} //출력 2, 3, 4, 5, 6 headIndex:6, tailIndex: 6