티스토리 뷰

반응형

Array

  1. Declaration

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

     const fruits = ['apple', 'banana'];
     console.log(fruits[1]);
     // banana
     console.log(fruits[2]);
     // undefined
  3. Looping over an array

    1. for 사용

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

       for (let fruit of fruits) {
        console.log(fruit);
       }
    3. forEach 사용

       fruits.forEach(function (fruit, index, array) {
           console.log(fruit, index, array);
       });
       // apple 0 ["apple", "banana"]
       // banana 1 ["apple", "banana"]
  4. Addition, deletion, copy

    • push: add an item to the end

    • pop: remove an item from the end

      fruits.push("peach");
      console.log(fruits);
      // ["apple", "banana", "peach"]
      fruits.pop();
      console.log(fruits);
      // ["apple", "banana"]
    • unshift: add an item to the beginning

    • shift: remove an item from the beginning

      fruits.unshift("peach");
      console.log(fruits);
      // ["peach", "apple", "banana"]
      fruits.shift();
      console.log(fruits);
      // ["apple", "banana"]
    • shift, unshift는 push, pop에 비해 매우 느림

    • splice: remove an item by index position

      fruits.push("peach", "grape");
      console.log(fruits);
      // ["apple", "banana", "peach", "grape"]
      fruits.splice(2);
      console.log(fruits);
      // ["apple", "banana"]
      fruits.push("peach", "grape");
      console.log(fruits);
      // ["apple", "banana", "peach", "grape"]
      fruits.splice(2, 1);
      console.log(fruits);
      // ["apple", "banana", "grape"]
      fruits.splice(2, 1, "pear", "orange");
      console.log(fruits);
      // ["apple", "banana", "pear", "orange"]
    • concat: combine two arrays

      const fruits2 = ["peach", "grape"];
      const newFruits = fruits.concat(fruits2);
      console.log(newFruits);
      // ["apple", "banana", "pear", "orange", "peach", "grape"]
  5. Searching

     console.log(fruits);
     // ["apple", "banana", "pear", "orange"]
     console.log(fruits.indexOf("apple"));
     // 0
     console.log(fruits.indexOf("coconut"));
     // -1
     console.log(fruits.includes("orange"));
     // true
     console.log(fruits.includes("coconut"));
     // false
     fruits.push("banana");
     console.log(fruits);
     // ["apple", "banana", "pear", "orange", "banana"]
     console.log(fruits.indexOf("banana"));
     // 1
     console.log(fruits.lastIndexOf("banana"));
     // 4
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함