TIL/JavaScript

배열(기초)

han1693516 2022. 5. 21. 22:38

 배열
    타 언어와 다르게, 한 배열에 다양한 자료형 넣을 수 잇음
          ex) 정수, 문자 한 번에 넣기 가능(하지만 지양해야)

    array declaration
       const arr1 = new Array();
       const arr2 = [1,2]; // more used

    index position
       const fruits = ['apple', 'banana'];
       console.log(fruits);
       console.log(fruits.length) // 2
       console.log(fruits[0]) // apple 출력
       console.log(fruits[3]) // undefined(정의 X)

     looping array
         1. using for loop
              for(let i=0;i<fruits.length;i++)
                  console.log(fruits[i]);

         2. using for of
               for(let fruit of fruits)
                   console.log(fruit)

         3. using forEach(callbackfn (value, index, array), thisArg?:(?는 parameter를 써도 되고, 안 써도 된다는 뜻)) 
            cf1> callback function을 받아옴
            cf2> 함수 호출이나 api 쓸 시 무작정 쓰지 말고 
                   선언된 곳으로 와서 이 함수는 무엇이고 파라미터는 무엇인지, 
                    return되는 값은 무엇인지 확인해야 도움됨
            cf3>forEach는 배열 내부 요소의 개수만큼 callback function이 반복됨
                callback 내부의 parameter는 배열의 value, 그 value의 index, 그리고 배열 그 자체를 받아옴
            cf4> 보통 value, index, array중 array는 거의 쓰지 않음
            
           ex) let fruits = ['apple', 'banana', 'grape']
                fruits.forEach(function(fruit(배열의 요소가 저장됨), number(배열의 index가 저장됨){
                     console.log(fruit);
                     console.log(number);
                 })

            익명 함수는 arrow function으로 바꿀 수 잇음
                fruits.forEach((fruit, number)=>{
                   console.log(fruit)
                   console.log(number)
               })

   
   add, delete, copy
         push : add item to the end of array
               fruits.push('strawberry')

         pop : remove item from the end     
               fruits.pop() // strawberry 삭제

         unshift : add an item to the beginning
               fruits.unshift("apple") // 앞에 apple 추가

         shift : remove an item from the beginning
                fruits.shift(); // 앞 요소 삭제

        중요 : shift, unshift are slower than push, pop
                   shift, unshift는 배열의 모든 요소를 움직여야 하지만
                   push, pop은 배열의 마지막 요소만 건드림
                       ex) push - 배열의 마지막에 요소 추가
                            pop - 배열 마지막 요소 삭제
                            unshift - 배열의 0번째에 요소 추가 후 원래 요소들은 1칸씩 밀려남
                            shift - 배열의 0번째 요소 삭제 후 뒤 요소 앞으로 1칸 이동

          
       splice(start :number, deleteCount?: number) : remove an item by index position
            fruits - ['apple', 'grape', 'banana', 'lemon', 'tomato']
            fruits.splice(1) // index 1부터 전부 삭제 ,'grape'부터 전부 삭제됨
            fruits.splice(1,1)//index 1부터 1개 삭제, 'grape'만 삭제됨
            fruits.splice(1,2)//index 1부터 2개 삭제, 'grape', 'banana' 삭제됨
            fruits.splice(1,2,'melon', 'pear') 
            //'grape', 'banana' 삭제되고 그 자리에 'melon', 'pear' 들어감
       
        concat : combine two array
           const arr1 = ['a', 'b']
           const arr2=['c', 'd']
           const arr3=arr1.concat(arr2); // arr1, arr2가 합쳐진 배열이 arr3에 저장
           

 
searching
        indexOf(value) // find the index
             ex) console.log(arr1.indexOf('a')); // 0
                  console.log(arr1.indexOf('b')); // 1
                  console.log(arr1.indexOf('x')) // -1(배열에 존재 X) 
              
        includes(value) // if value is in the array
             console.log(arr1.includes('a')) // true
             console.log(arr1.includes('x')) // false

        lastIndexOf // 제일 마지막에 있는 요소의 위치 파악
             arr1 = ['a', 'b', 'a']
             console.log(arr1.lastIndexOf('a')) // 2 출력
             console.log(arr1.indexOf('a')) // 0 출력

'TIL > JavaScript' 카테고리의 다른 글

Class  (0) 2022.07.15
배열 관련 함수  (0) 2022.05.22
객체(object)  (0) 2022.05.21
JavaScript - 조건문, 반복문, 형변환  (0) 2022.05.08
JavaScript - 함수  (0) 2022.05.08