[JS : array, 배열개념과 APIs 총정리]

Teasan·2020년 9월 27일
0

JavaScript

목록 보기
2/15
post-thumbnail

<Array, 배열>

1. Declaration

~ 배열 만들기 첫번째 ~

const arr1 = new Array();

~ 배열 만들기 두번째 ~

const arr2 = [1, 2];
  • 총 길이가 2개인 배열이 만들어졌다. 0번째 index는 1이라는 value값, 1번째 index는 2라는 value값이 들어있다.
  • array배열이 index를 기준으로 data가 저장이 되기 때문에 index를 활용해서 data를 다룰 수 있는지가 중요하다.

2. Index position

const fruits = ['사과', '바나나'];

console.log(fruits);
// 결과 : ['사과', '바나나']

해당 array배열의 index.length 를 구해보면,

console.log(fruits.length);
// 결과 : 2

array배열은 숫자 index를 전달하게 되면 그 index에 해당하는 value값을 받아올 수 있다.

console.log(fruits[0]); // 사과
console.log(fruits[1]); // 바나나

만약, index 밖에 있는 index를 접근하게 되면,

console.log(fruits[2]); // undefined

보통 배열의 첫번쨰 아이템을 찾을 때는 0을 많이 쓰며, 배열의 마지막 아이템을 찾을 때는,

console.log(fruits[fruits.length - 1]) 
// 마지막 index data에 접근할 수 있다.
  • 배열은 index가 0부터 시작하기 때문에, 총 길이(length)에 -1을 하면 제일 마지막 index를 받아올 수 있기 때문이다.

3. Looping over an array

  • print all fruits : fruits array 배열 전체를 출력하기
console.log(fruits.array);
// (2) [‘사과’, ‘바나나’]

a. for loop

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

// 사과
// 바나나

b. for of

for(let fruit of fruits) { 
// fruit이라는 변수에 fruits이라는 배열을 할당.
    console.log(fruit);
}

// 사과
// 바나나

c. forEach

  • forEach는 callback 함수를 받아온다.
    forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
  • Calls a defined callback function on each element of an array, and returns an array that contains the results.
  • array배열 안에 들어있는 value값마다 우리가 전달한 action callback 함수를 수행한다는 뜻.

Example) array.

const fruits = ['사과', '바나나’];
fruits.forEach()

forEach 분석하기

forEach(callbackfn: (value: T, index: number, array: T[]) => void,

우리가 전달한 callback 함수를 value값 마다 호출해주고 callback 함수에는 총 세가지의 인자(value, index, array)가 들어온다는 뜻.

1. Value : callback함수 안의 value값이 전달되고,
2. Index : 그 value값이 들어있는 index가 들어오고,
3. Array : 전체적인 array배열도 전달을 받을 수가 있다.

thisArg?: any): void;

‘사과'가 들어있는 index가 나의 callback 함수로 들어오고,’ 바나나'와 '바나나가 들어있는 index[1]’ 가 callback 함수로 들어온다는 것을 알수 있음.

fruits.forEach(function () {
    console.log('he');
});

// 결과 : he 가 2번 출력되었다.
// 해설 : 사과, 바나나 총 2개가 들어있기 때문에.

fruits.forEach(function (fruit, index, array) {
    console.log(fruit);
});

// 사과
// 바나나

fruits.forEach(function (fruit, index, array) {
    console.log(fruit, index);
});

// 사과 0
// 바나나 1
  • forEach에서(array)를 출력하면, 해당 array 전체가 출력된다.
    그렇기에, 보통 forEach에서(array)는 불러오지 않음.
fruits.forEach(function (fruit, index, array) {
    console.log(fruit, index, array);
}); 

위의 식을 더 간단하게 arrow function을 이용해서 작성할 수도 있다.

fruits.forEach((fruit) => { console.log(fruit)});
// 사과
// 바나나

"forEach는 array배열안에 들어있는 value값들 마다 내가 전달한 function함수를 출력한다."

4. Add, Delete, Copy

push( )
pop( )
unshift( )
shift( )
splice( )
concat( )

Example) array.

const fruits = ['사과', '바나나’];
fruits.forEach()

push( )

  • add an item to the and : 어떤 value들을 array배열의 제일 뒤에 놓고 싶을 때 사용.
fruits.push('딸기', '복숭아');

console.log(fruits);
// (4) ['사과', '바나나', '딸기', '복숭아']

pop ( )

  • remove an item form the end : 어떤 value들을 array배열의 제일 뒤에서부터 지우고 싶을 때 사용.
fruits.pop();

console.log(fruits);
// (3) ['사과', '바나나', '딸기']
// index 맨 뒤에 있던 value 값이 지워져있음을 확인할 수 있다.

unshift( )

  • add an item to the benigging : 어떤 value들을 array배열의 제일 앞에 놓고 싶을 때 사용
fruits.unshift('키위', '레몬');

console.log(fruits);
// (5) ['키위', '레몬', '사과', '바나나', '딸기']

shift( )

  • remove an item from the benigging : 어떤 value들을 array배열의 제일 앞에서부터 지우고 싶을 때 사용.
fruits.shift();

console.log(fruits);
// (4) ['레몬', '사과', '바나나', '딸기']

여기서 중요한 tip.

  • shift( )와 unshift( ) 는 정말 느리다.
  • pop( )이나 push( ) 처럼 뒤에서부터 넣고 뺴는 방법은 빈 공간에 data를 지우고 빼는 것에 유용하지만
  • shift( )와 unshift( ) 처럼 앞에서부터 넣고 빼는 방법은 원래 자리하고 있던 data들을 이동해야하기 때문에 처리속도가 느릴 수 밖에 없다. 그렇기에 가능하면 pop( )이나 push( ) 를 사용하는 것이 좋다.
  • 제일 뒤에서 item을 접근하는 것은 속도가 빠르며, 중간에 data를 넣고 빼는 것도 index를 활용하기 때문에 빠르다.
  • array배열의 길이가 길면 길수록 전체적으로 움직여야 되는 것들이 많기 때문에 더욱 처리속도가 느려질 수 밖에 없다.

splice( )

splice(start: number, deleteCount?: number): string[ ]
  • remove an item by index position : 아이템을 지정된 position에서 지우고자 할 때 사용한다.
fruits = ['레몬', '사과', '바나나', '딸기'];

fruits.splice(1);
console.log(fruits);
// ['레몬']

원하는 index만 지정하고 몇개를 지울 건지 설정하지 않으면 지정한 index 부터 끝까지 지워버린다.

그렇다면, 원하는 index를 지정하고, 몇개를 지울건지도 설정해보자.

fruits = ['레몬', '사과', '바나나', '딸기'];
fruits.splice(1, 1); 
// 원하는 index[1], 지우고 싶은 갯수(1) 설정.

console.log(fruits);
// (3) ['레몬', '바나나', '딸기'];

우리가 설정한 해당 index[1]가 우리가 설정한 갯수(1)에 따라 지워졌음을 알수있다.

지우고 싶은 index를 지정하고, 몇개를 지울건지도 설정하며, 또 다른 value를 추가할 수 있도록 해보자.

fruits = ['레몬', '사과', '바나나', '딸기'];
fruits.splice(1, 1, '복숭아', '키위');

console.log(fruits);
// 순서1. ['레몬', /* '사과' */ 지워짐 , '바나나', '딸기'];
// 순서2. ['레몬', /* '복숭아', '키위' */ 들어감 , '바나나', '딸기'];

// 결과 : (5) ['레몬', '복숭아', '키위', '바나나', '딸기'];

concat( )

concat(...items: ConcatArray<T>[]): T[ ];
  • combine two arrays
fruits = ['레몬', '복숭아', '키위', '바나나', '딸기'];
const fruits2 = ['오렌지','라임']; 
// 새로운 array를 만들어서

const newFruits = fruits.concat(fruits2); 
// concat API를 이용하여 기존의 fruits array와 결합한뒤, 변수로 선언하면

console.log(newFruits);
// 결과 : (7) ['레몬', '복숭아', '키위', '바나나', '딸기', '오렌지', '라임'];

기존의 fruits[array]와 fruit[array]가 결합되었음을 알 수 있다.

5. Searching

Example) array.

const fruits = ['레몬', '복숭아', '키위', '바나나', '딸기', '오렌지', '라임']

indexOf

  • find the index : array 배열 안에 어떤 value값이 몇번째 index에 있는지 알고 싶을 때 유용하다.
  • array배열에 특정 value값이 몇번째 index에 있는지 검사하는 API
console.log(fruits.indexOf('복숭아'));
// 1
console.log(fruits.indexOf('바나나'));
// 3

만약에 특정 value값이 해당 array배열 밖에 있다면 ?

console.log(fruits.indexOf('코코넛'));
// -1
// 즉, array배열안에 해당하는 value값이 없을 때는 -1이 출력이 된다.

includes

  • array배열에 특정 value값이 있는지 없는지 검사하는 API
  • boolean(true, false) 으로 출력한다.
    fruits = ['레몬', '복숭아', '키위', '바나나', '딸기’];
console.log(fruits.includes('복숭아'));
// true
console.log(fruits.includes('코코넛'));
// false

lastIndexOf

  • 제일 마지막으로 해당하는 값을 만나면 그 값이 들어있는 마지막 Index를 리턴하게 된다.
fruits = ['레몬', '복숭아', '키위', '바나나', '딸기’];

// push() : index 제일 마지막 번쨰에 추가하는 API
fruits.push('레몬'); 

console.log(fruits);
// ['레몬', '복숭아', '키위', '바나나', '딸기', '레몬'];

// indexOf : 제일 첫번째로 해당하는 값을 만나면 그 값이 들어있는 첫번째 Index를 리턴하게 된다.
console.log(fruits.indexOf('레몬'));
// 0

// lastIndexOf : 제일 마지막으로 해당하는 값을 만나면 그 값이 들어있는 마지막 Index를 리턴하게 된다.
console.log(fruits.lastIndexOf('레몬'));
// 5

출처 : 드림코딩 by 엘리 유투브 채널의 자바스크립트 시리즈 영상을 기반으로 작성했습니다. https://youtube.com/playlist?list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2

profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글