ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JavaScript] 배열(Array)
    JavaScript 2022. 2. 17. 20:50
    728x90
    반응형
    1. 배열 선언
    2. 인덱스
    3. 배열의 모든 원소 방문하기
    4. Push, pop, unshift, shift
    5. Searching

     

    1. 배열 선언

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

     

    2. 인덱스

    const fruits = ['🍎', '🍌'];
    console.log(fruits);
    console.log(fruits.length);
    console.log(fruits[0]);
    console.log(fruits[1]);
    console.log(fruits[2]); // -> undefined
    console.log(fruits[fruits.length -1 ]);

     

    3. 배열의 모든 원소 방문하기

    console.clear();
    
    // (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. Push, Pop, Unshift, Shift

    // push: add an item to the end
    fruits.push('🍓', '🍑');
    console.log(fruits);
    
    // pop: remove an item from the end
    fruits.pop();
    console.log(fruits);
    
    // unshift: add an item to the begining
    fruits.unshift('🍋');
    console.log(fruits);
    
    // shift: remove an item from the begining
    fruits.shift();
    console.log(fruits);
    
    // 주의@! 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, 1, '🍇', '🍍');
    console.log(fruits);
    
    // combine two arrays
    const fruits2 = ['🍐', '🍅'];
    const newFruits = fruits.concat(fruits2);
    console.log(newFruits);

     

    5. Searching

    // find the index
    console.clear();
    console.log(fruits);
    console.log(fruits.indexOf('🍎'));
    console.log(fruits.indexOf('🍉'));
    console.log(fruits.indexOf('🍍'));
    
    // includes -> boolean
    console.log(fruits.includes('🍉'));
    console.log(fruits.includes('🥥'));
    
    // lastIndexOf
    console.clear();
    fruits.push('🍎');
    console.log(fruits);
    
    console.log(fruits.indexOf('🍎'));
    console.log(fruits.lastIndexOf('🍎'));
    LIST

    'JavaScript' 카테고리의 다른 글

    [JavaScript] Callback  (0) 2022.02.19
    [JavaScript] JSON  (0) 2022.02.19
    [JavaScript] 유용한 배열(Array) API 10가지  (0) 2022.02.17
    [JavaScript] 객체(Object)  (0) 2022.02.17
    [JavaScript] Class와 Object  (0) 2022.02.16
Designed by Tistory.