본문 바로가기

Front-end/Javacript

자바스크립트 Tutorial By Ellie (6)

 8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리

 

비슷한 종류의 데이터를 묶어서 한곳에 보관하는것이 "자료구조"

 

Object

 

자료구조

 

Object 자료구조의 차이

 

Object : 서로 연관된 특징과 행동을 묶어놓는

 

자료구조 : 비슷한 타입의 Object들을 묶어놓는  

 

다른언어에서는 동일한 타입에 Object 담을 있다

 

JavaScript === dynamically typed language

자바스크립는 담을 있지만 좋지 않다.

 

자료구조 알고리즘 : 어떤상황에 써야하는지 공부

 

배열

  • 칸칸히 모여있는 자료구조
  • Index지정되어있음        
  • Index 접근에 중간중간 삭제가능하다
  • // Array🎉

    // 1. Declaration
    const arr1 = new Array();
    const arr2 = [1, 2];

    // 2. Index position
    const fruits = ['🍎', '🍌'];
    console.log(fruits);
    console.log(fruits.length);
    console.log(fruits[0]);
    console.log(fruits[1]);
    console.log(fruits[2]);
    console.log(fruits[fruits.length - 1]);
    console.clear();
    // 3. Looping over an array
    // 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('🍓', '🍑');
    console.log(fruits);

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

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

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

    // note!! shift, unshift are slower than pop, push
    // splice: remove an item by index position
    fruits.push('🍓', '🍑', '🍋');
    console.log(fruits);
    fruits.splice(1, 1);
    console.log(fruits);
    fruits.splice(1, 0, '🍏', '🍉');
    console.log(fruits);

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

    // 5. Searching
    // indexOf: find the index
    console.clear();
    console.log(fruits);
    console.log(fruits.indexOf('🍎'));
    console.log(fruits.indexOf('🍉'));
    console.log(fruits.indexOf('🥥'));

    // includes
    console.log(fruits.includes('🍉'));
    console.log(fruits.includes('🥥'));

    // lastIndexOf
    console.clear();
    fruits.push('🍎');
    console.log(fruits);
    console.log(fruits.indexOf('🍎'));
    console.log(fruits.lastIndexOf('🥥'));