티스토리 뷰

1. Decalaration

배열을 만드는 두 가지 방법

const arr1 = new Array();
const arr1 = [1, 2];

2. Index position

배열은 인덱스 값이 1 2 3이 아닌 0 1 2로 된다는 걸 명심!

const fruits = ['a','b'];
console.log(fruits); // a, b 둘다 출력됨
console.log(fruits.length); // 배열의 크기인 2가 출력됨
console.log(fruits[0]); // 배열의 첫번째인 a가 출력됨
console.log(fruits[1]); // 배열의 두번째인 b가 출력됨
console.log(fruits[2]); // undefined가 출력됨(이는 인덱스2는 배열에 없기 때문)
console.log(fruits[fruits.length - 1]); // 마지막 데이터는 이런식으로 접근함

3. Looping over an array

과일 배열을 출력하는 3가지 방식이다.

foreach는 괄호 안에 각각의 배열마다 액션을 취하게 해주는 함수이다.
// print all fruits

// a. for
for(let i = 0; i < fruits.length; i++){
    console.log(fruits[i]);
}

// b. for of
for(let fruit of fruits){
    console.log(fruit);
}

// c. forEach
fruits.forEach((fruit) => console.log(fruit));

4. addtion, deletion, copy

// push : add an item to the end
fruits.push('a','b');
console.log(fruits);

//pop : remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);

//unshift : add an item to the benigging
fruits.unshift('c','d');
console.log(fruits);

//shift : remove an item from the benigging
fruits.shift();
fruits.shift();
console.log(fruits);

// shift unshift는 pop과 push보다 매우 느리니 사용 자제
// splice : remove an item by index position
fruits.push('a','b','c');
console.log(fruits);
fruits.splice(1,1); // 1부터 1까지 즉 인데스가 1인 위치를 없앰
console.log(fruits);
fruits.splice(1,1,'a','b'); // 인덱스가 1인 곳을 없애고 a랑 b를 집어넣음
console.log(fruits);

// combine two arrays
const fruits2 = ['f','e'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

shift unshift는 2번째 데이터를 3번째에 넣고 1번째 데이터를 2번째에 넣고 0번째에 새로운 데이터를 집어넣어야 되는 

과정 속에서 시간을 잡아먹는다.

 

fruits.splice(1);

이런식으로 splice를 쓰게 되면 우리가 지정한 인덱스를 포함하여 뒷부분을 모두 지워버린다.

그래서 위처럼 지정해줘서 사용한다. 또한 지우고 채워 넣는 것도 가능하다.

const newFruits = fruits.concat(fruits2);

. concat(배열)을 이용하여 두 배열을 합칠 수 있다.

5. searching

아래와 같이 유용하게 검색이 가능하다

// index of : find the index
console.clear();
console.log(fruits); 
console.log(fruits.indexOf('a')); // 인덱스 위치를 알려줌 
console.log(fruits.indexOf('b')); 
console.log(fruits.indexOf('q')); //만약 없으면 -1을 출력 

// includes
console.log(fruits.includes('b')); // 있으면 true
console.log(fruits.includes('q')); // 없으면 false

// lastIndexOf
fruits.push('a');
console.log(fruits.indexOf('a')); //맨 처음 사과의 인덱스 출력
console.log(fruits.lastIndexOf('a')); //맨 마지막 사과의 인덱스 출력

만약 라이브러리 내용이 궁금하다면 윈도우는 ctrl을 누른 뒤 클릭하면

 * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.
     * @param searchElement The value to locate in the array.
     * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.
     */
    lastIndexOf(searchElement: T, fromIndex?: number): number;

다음과 같이 친절한 설명이 나온다