TIL

[TIL-90] 위코드 사전스터디 자바스크립트 07 배열

어포능이만두 2022. 1. 7. 10:08

배열

  • 요소 삭제하기 : 메서드 이용
    • array.pop() : 마지막 요소 삭제
    • array.shift() : 맨 앞 요소 삭제
    • array.splice(n, m) : 인덱스 n번 요소부터 m개 삭제. 세번째 인자를 쓰면 그 자리에 추가될 요소가 됨.
    • let array_new = array.slice(n, m) : 배열 내의 특정한 요소의 인덱스 범위에 따라 새로운 배열을 리턴.
      • 원본 배열을 변형하는 게 아니라, 원본 배열에서 인덱스 번호 n부터 m 전까지의 요소만 가진 새로운 배열을 만듦. 따라서 새로운 변수로 선언하여 저장해줘야함.
      • 첫번째 인자에 음수가 들어가는 경우, 끝에서부터 해당하는 숫자 만큼의 요소를 배열에 담아 리턴.
      • [참고] https://im-developer.tistory.com/103 [JS/Array] slice()와 splice()의 차이점
  • 중첩된 배열(다차원배열)
    •  const array = [ 100, 400, [1, 2, 4], 20, 6 ];
  • filter(작동할 함수) 
    • String.includes("찾을 문자열", 찾기 시작할 위치) : "찾을 문자열"이 포함되어있는지 여부를 확인하여 불리언으로 반환.
      • 예) abcde.includes("c", 2) => true
             abcde.includes("c", 3) => false
    • [에러] Stack Trace: TypeError: Cannot read property 'includes' of undefined at filtered
      let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
      
      function filtered (value) {
        return value.includes("ap");
      }
      
      fruits.filter(filtered);​
      • 에러는 뭔소린지 모르겠음.
      • 마지막 줄에 필터 메서드 사용한 결과를 새로운 배열에 할당해주지 않음. 그럼 어떻게 되는 거지?
        • let result = fruits.filter(filtered); 라고 해줘도 패스 안 됨. 물론 console.log(result) 하면 잘 뜸.
      • 마지막줄 console.log 하면 결과 잘 뜨는데 패스 안 됨.
    • [에러] Stack Trace: TypeError: Cannot read property 'filter' of undefined at filtered
      let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
      
      function filtered (array) {
        const result = array.filter((value)=> value.includes("ap"));
        return result;
      }
      
      console.log(filtered(fruits));​
      • 또 에러 떴는데 아까부터 왜 porperty를 못 읽고 난린지 모르겠음.
      • 실행하면 콘솔에 [ 'apple', 'grapes' ] 잘 뜨는데 왜 틀렸는지 이상함.
      • [해결] 아래 참조. filtered 함수에 fruits를 인자로 넣어줄 필요 없이 함수 안에서 array 인자 자리에 fruits 배열을 바로 써줘야 함. 그래야 filtered() 실행만으로 테스트 결과가 나올 수 있음. 
    • [해결] 테스트가 원하는 걸 깨달음.
      function filtered () {
        const result = fruits.filter((value)=> value.includes("ap"));
        return result;
        }
      
      module.exports = { filtered };​
      • module.exports = { filtered }; 라는 부분이 테스트를 검증해주는 것 같은데, filtered만으로 작동하는지 확인되려면 filtered 함수가 작동함으로써 결과가 나와야 함. 이 함수를 filter 메서드의 콜백함수로 사용하면 안 됨. 
  • array1.concat(array2) : array1에 array2 요소들을 합쳐 새로운 배열을 만듦.
    • 기본적으로 중복된 요소를 거르지 않고 모두 추가함.
    • filter 메서드를 사용해서 중복 거를 수 있음.
      let array = [  1, 2, 3, 4, 5, 3, 4, 5, 6, 7  ]
      
      let eraseDuplicates = array.filter((el,index)=>array.indexOf(el)===index);
      
      console.log(eraseDuplicates);    //[ 1, 2, 3, 4, 5, 6, 7 ]​
      • [질문] (el, index)는 뭔가? 그 값을 어디서 받아오나? 어떻게 정해짐?
        • filter(callbackFunction, thisAgr) 2개의 인자를 가지며, callbackFunction 안에서 3개의 인자 (element, index, array)를 가지는데 첫번째 부분인 element 인자만 필수로 지정되어야하고 나머지는 선택적.
        • https://cmelcmel.tistory.com/91
      • indexOf(searchElement, fromIndex) : (배열 안에 위치한 요소, 검색이 시작될 인덱스 번호)
  • populating : new Array(n)
    • 새 배열로 선언해보면 빈 배열이지만 n개의 공간이 있는 배열이 생김.
    • 값은 나중에 따로 할당해주면 됨.

 


 

공부할 것

  • Bracket Notation
  • map()
  • Set 객체