JS (ES6 & above) - 배열
■ JS 배열
> index를 가지고 있음
> 동일한 type의 자료들을 묶어서 가지고 있는 것이 일반적
■ 선언 방법
> 다음의 두가지가 있음
const arr1 = new Array();
const arr2 = [1, 2];
■ Index position
> Object에 key값으로 value에 접근할 수 있는 것 처럼, index 값으로 array 값에 접근 가능
const fruits = ['🍅', '🍓'];
console.log(fruits);
console.log(fruits.length);
// first , second index
console.log(fruits[0], fruits[1]);
console.log(fruits[2]); // undefined
console.log(fruits[-1]); // not like python, no -1 index
console.log(fruits[fruits.length - 1]); //last item
※ - 1 index는 없음 (파이썬과 다름!)
■ Looping over an array
for(let i=0; i < fruits.length; i++){
console.log('fruits.length : ',fruits[i]);
}
>>>
fruits.length : 🍅
fruits.length : 🍓
for(let fruit of fruits){
console.log('for of : ',fruit);
}
>>>
for of : 🍅
for of : 🍓
fruits.forEach( (value, index, total_array)=>{
// callback으로 3가지를 받아올 수 있음
console.log('forEach value : ', value);
console.log('forEach index : ', index);
console.log('forEach total_array : ', total_array);
})
>>>
forEach value : 🍅
forEach index : 0
forEach total_array : [ '🍅', '🍓' ]
forEach value : 🍓
forEach index : 1
forEach total_array : [ '🍅', '🍓' ]
■ Addition, deletion, copy
1) 추가 / 삭제
> push, pop
> unshift (삽입되는 애는 shift 안되므로),
shift
[ '🍅', '🍓'] (원본)
// push : add item to the end
fruits.push('🥝', '🍍');
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝', '🍍' ]
// pop : remove item from end
fruits.pop();
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝' ]
// unshift : add and item to the beginning
fruits.unshift('🧀');
console.log(fruits);
>>>
[ '🧀', '🍅', '🍓', '🥝' ]
// shift : remove an item in the beginning
fruits.shift('🧀');
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝' ]
※ shift / unshift는 linked list처럼 작동해서 (아마도) 배열 길이 N 만큼 뒤로 밀거나 땡겨와야 하기 때문에 느릴 수 있음
추가 삽입 / 삭제시 item들을 옮겨야 함 → O(N) 이므로 push / pop 사용을 권장
■ Splice : 지정 index 작업
> ? 는 optional arg : 있어도 되고 없어도 되는 arg
시작 index 지점 ~ 원하는 개수 만큼 반복 삭제
1) deleteCount 없을 때
console.log(fruits);
fruits.splice(1);
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝', '🍍' ]
[ '🍅' ]
2) deleteCount 있을 때
console.log(fruits);
fruits.splice(1, 1);
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝', '🍍' ]
[ '🍅', '🥝', '🍍' ]
3) item 항목이 추가된 경우
console.log(fruits);
fruits.splice(1, 1, ['🍖','🍗','🥩'], '🥩');
console.log(fruits);
>>>
[ '🍅', '🍓', '🥝', '🍍' ]
[ '🍅', [ '🍖', '🍗', '🥩' ], '🥩', '🥝', '🍍' ]
4) concat로 array 두개 연결
const fruits_2 = ['🍕'];
console.log('concat : ',fruits.concat(fruits_2));
>>>
[ '🍅', [ '🍖', '🍗', '🥩' ], '🥩', '🥝', '🍍', '🍕' ]
■ Searching Index
> O(N)
// find the index
console.log(fruits);
>>>
[ '🍅', [ '🍖', '🍗', '🥩' ], '🥩', '🥝', '🍍', '🍕', '🍕' ]
console.log(fruits.indexOf('🥝'));
>>>
3
console.log(fruits.indexOf('')); // non existing
>>>
-1
// check existance
console.log(fruits.includes(''));
>>>
false
// get last index of multiple search results
console.log(fruits.lastIndexOf('🍕'));
>>>
6
// get first index of multiple search results
console.log(fruits.indexOf('🍕'));
>>>
5
참조 :
www.youtube.com/watch?v=yOdAVDuHUKQ&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=8&t=1s