8. Array와 APIs

jean·2021년 2월 7일
0

Object?

자료구조?
객체를 모아놓은 것을 자료구조라고 한다.
보통 다른 프로그래밍 언어에서는 자료구조에 동일한 타입의 객체만 담을 수 있지만,
자바스크립트는 type이 동적으로 (런타임에) 결정되는 dynamically typed language이므로 자료구조 안에 아무 타입이나 뚝배기처럼 담을 수 있는 이런 미친 짓이 가능하다!
가능은 하지만 이런식으로 프로그래밍을 하는 것은 좋지 않다.

나중에 프로그램을 짤 때, 삽입, 삭제, 검색, 정렬에 따라 자료구조를 잘 선택하는 것이 중요하다.

Array?
1. Declaration
const arr1 = new Array();
const arr2 = [1, 2]; // 더 흔한 방법

  1. index position

  2. looping
    3-1. for loop
    3-2. for of
    for (let fruit of fruits) {}

    3-3. for each API
    fruits.forEach( function(fruit, index, array) {} );

    forEach API의 callback 함수에는 3개의 인자가 들어간다. (하지만 3번째 인자인 array는 보통 잘 들어가지 않으므로 생략해도 된다.)
    Ctrl + 클릭으로 API의 사용법을 항상 확인하면서 코딩하는 것이 좋다.
    이름 있는 함수는 arrow function으로 변환할 수 있으므로 아래와 같이 쓴다.
    fruits.forEach((fruit, index) => {});

    만약 index를 출력하고 싶지 않다면, 아래와 같이 쓸 수도 있다.
    fruits.forEach((fruit) => console.log(fruit));

  3. add, delete, copy
    push: add an item to the end
    fruits.push('apple');

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

**note!! shift, unshift are slower than pop, push
shift: remove an item from the beginning(오른쪽으로 밀어버려서 앞쪽 인덱스를 비우는 것이라 shift이다!)
fruits.shift();

unshift: add an item from the beginning
fruits.unshift('apple');

  1. splice
    배열 중간의 값을 선택해서 (원하는 만큼) 지우거나, 지운 자리에 새로운 값으로 채우는 게 가능!

fruits.splice(1); // index 1번째 값부터 뒤까지 몽땅 지운다!
fruits.splice(1, 1);// index 1번째 값부터 1개만 지운다!
fruits.splice(1, 1, 'melon', 'peach'); // index 1번째 값부터 1개만 지우고, 그 자리에 'melon'과 'peach'를 넣는다!

  1. concat: combine two arrays
    const newFruits = fruits.concat(fruits2);
    fruits 배열과 fruits2 배열을 합친다.

  1. searching: find the index
    검색할 수 있는 API들

fruits.indexOf('apple'); // 배열 안에서 'apple'이 몇 번째 인덱스에 있는지 찾아준다. 배열 안에 해당 값이 없을 경우 -1이 출력된다.

fruits.includes('peach'); // 배열 안에 'peach'가 있는지 true/false로 확인해준다.

  1. lastIndexOf
    fruits.push('apple');
    배열 안에 여러 개의 같은 값('apple')이 있을 경우,
    .indexOf는 무조건 첫번째 index 값을 출력하고
    .lastIndexOf는 마지막 index 값을 출력한다.

0개의 댓글