JS2_06_Array


Array


Declaration

//1.
const arr1 = new Array();
//2.
const arr2 = [1, 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]); //마지막 인덱스

Looping over an array

  • print all fruits
  • 1) for

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

    2) for..of

    for (const fruitV of fruits) {
      console.log(fruitV);
    }

    3)forEach(コールバック関数)

    fruits.forEach((value, index) => console.log(value, index));
    console.log("---------------------------------");
    
    fruits.forEach((value) => console.log(value));
    console.log("===================================");

    Add, Delete


    push

  • add an item to the end
  • fruits.push("딸기", "복숭아");
    console.log(fruits);

    pop

  • remove an item from the end
  • fruits.pop();
    console.log(fruits);
    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);
    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);

    concat

  • combine two arrays
  • const fruits2 = ["배", "구아바"];
    const newFruits = fruits.concat(fruits2);
    console.log(newFruits);

    Searching


    indexOf

  • find the index
  • console.log(fruits);
    console.log(fruits.indexOf("사과"));
    console.log(fruits.indexOf("수박"));
    console.log(fruits.indexOf("구아바"));	//없으면 -1

    includes

  • (真/偽)
  • があるかどうか
    includes
    console.log(fruits.includes("수박"));
    console.log(fruits.includes("구아바"));

    lastIndexOf

  • -
  • fruits.push("사과");
    console.log(fruits);
    console.log(fruits.indexOf("사과"));
    console.log(fruits.lastIndexOf("사과"));