ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Javascript 잦은 망각에 도저히 안되겠어서 하는 array 내장 메소드 정리__이 정돈 기억하자
    Develop/Javascript 2020. 6. 11. 03:03
    console.log('hihi');

    가자! array 내장 method 정리!!

    이전에는 결과가 새로운 array를 반환하는 함수만 정리했으나,

    이번엔 자주 쓰이거나 요긴하게 쓸 것들 정리!

    사용법 까지 정리해보자.!!


    새로운 배열을 반환하는 내장 method 들..

    Array.prototype.concat()
    • 이 함수는 매개변수로 주어진 값이나 배열을 사용될 배열과 합쳐서 반환함
    • 사용법 : array.concat([value1 [, value2 [, ...[valueN]]])
    • value에 들어갈 값 : 배열 or 값
    • 매개변수에 아무런 값도 넣지 않으면 array의 얕은 복사본만 반환
    • ※ 얕은 복사본 : 같은 주소를 참조하는 다른 변수를 의미함 (object 타입만 해당)
    • 예시
    const strings1 = ['a', 'b', 'c'];
    const strings2 = ['d', 'e']
    const numbers1 = [1, 2, 3];
    const numbers2 = [4, 5];
    
    strings1.concat(numbers1); // ['a', 'b', 'c', 1, 2,3]
    strings1.concat(numbers1, numbers2, strings2); // ['a', 'b', 'c', 1, 2, 3, 4, 5, 'd', 'e']
    strings1.concat(1, numbers2); // ['a', 'b', 'c', 1, 4, 5];

    Array.prototype.filter()
    • 주어진 test(callback)의 결과가 true인 원소들을 모아서 새로운 배열을 반환함
    • 사용법 : array.filter(callback(element [, index [, array]]) [, thisArg])
    • callback : filter로 사용될 함수
    • callback 의 매개변수들:  
      • element: 처리할 현재 원소
      • index: 처리할 현재 원소의 인덱스
      • array: filter를 호출한 배열
    • thisArg: callback을 실행할 때 this로 사용하는 값
    • ※ 아무런 원소도 test함수를 통과하지 못하면 빈 배열 반환
    • 예시 : 2의 배수 or 짝수들을 반환
    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; 
    let resultArr = arr.filter(number => number % 2 === 0);
    console.log(resultArr); // [2, 4, 6, 8, 0]
    

    Array.prototype.map()
    • 배열 내의 모든 원소들 각각에 대하여 함수(callback)을 처리를 한 결과들을 모아서 새로운 배열을 반환함
    • 사용법: array.map(callback(currentValue [, index[, array]] ) [, thisArg])
    • callback : 각 원소들에 대해 처리를 할 함수
      • callbck의 매개변수들:  currentValue: 처리할 현재 원소  index: 처리할 현재 원소의 인덱스  array: map을 호출한 배열
    • thisArg: callback을 실행할 때 this로 사용하는 값
    • ※ filter와 map이 매개변수의 형태가 같다.
    • 예시 : 각 원소들에게 2씩 더한 값들이 있는 배열을 반환
    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let resultArr = arr.map(number => number + 2);
    console.log(resultArr); // [3, 4, 5, 6, 7, 8, 9, 10, 11, 2]
    

    Array.prototype.slice()
    • 배열의 begin부더 end 바로 앞까지 얕은 복사본을 반환함
    • 사용법:  array.slice([begin [, end]])
    • begin: 추출을 시작할 인덱스,  음수면 배열의 끝에서부터의 길이 slice(-2)는 끝에서 두 개를 추출,  undefined일 때 0번 인덱스부터 slice(default가 0) ,  begin이 배열의 길이보다 크면 빈 배열 반환
    • end: 추출을 종료할 0 기준 인덱스 ( 그냥 처음부터 몇 번째에 있는 가를 나타냄) 음수면 배열의 끝에서부터의 길이 slice (2, -1)는 인덱스 2(3번째 원소) 부터 끝에서 두번째 원소까지 추출,  end의 값이 배열의 길이보다 크거나, 생략되면 배열의 끝까지 추출함
    • 예시 ( 마치 arr.slice( a, b) 에서 a는 인덱스의 형태, b는 그냥 사람이 세는 순번의 형태 )
    let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    let resultArr1 = arr.slice(3, 5);
    let resultArr2 = arr.slice(2, -2);
    
    console.log(resultArr1); // ['d', 'e'] 
    // 인덱스가 3인 'd'부터 5번째 원소인 'e'까지 출력
    console.log(resultArr2); // ['c', 'd' ,'e']
    // 인덱스가 2dls 'c'부터  -2를 했지만 끝에서 3번째 원소인 'e'까지 출력

    그 밖의 내장 method 들..

    Array.prototype.forEach()
    • 배열의 각각의 원소에 대해 주어진 함수를 처리함 -> 새로운 배열이 아닌 현재 배열에서 처리
    • 사용법: array.forEach(callback(currentValue [, index[, array]] ) [, thisArg]) -> map 과 같다. (즉 filter와 매개변수의 형태가 같음)
    • callback : 각 원소들에 대해 처리를 할 함수
    • callbck의 매개변수들
      • currentValue: 처리할 현재 원소
      • index: 처리할 현재 원소의 인덱스
      • array: map을 호출한 배열
    • undefined를 반환함. => 메소드 체인 불가능, 배열을 변형하지 않음
    • for문은 continue나 break로 제어 가능하지만,  forEach는 throw(예외)를 발생시키지 않으면 중간에 종료 불가능
    • forEach의 처리 범위는 처음 callback 호출 전에 설정됨, 호출되고 나서 배열에 추가되어도 그 원소에는 callback이 방문하지 않음
    • 배열이 줄어드는 경우는 있음,,;;(2번째 예시)  -> 'two'일 때 shift() 가 실행되면, 배열의 총 길이가 줄어듬 -> 다음 인덱스가 'four'에 해당하게됨 ( 'three'를 건너 뛰어버리는 결과가 됨)
    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let resultArr = arr.forEach(number => number + 2);
    console.log(resultArr); // undefined
    console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    arr.forEach(number => console.log(number));
    //1
    //2
    //3
    //4
    //5
    //6
    //7
    //8
    //9
    //0
    
    let words = ['one', 'two', 'three', 'four'];
    words.forEach(function(word) {
      console.log(word)
      if (word === 'two') {
        words.shift()
      }
    })
    // one
    // two
    // four 
    console.log(words); // ['two', 'three', 'four']

    Array.prototype.reduce()
    • 배열의 각 원소마다 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과로 만들어 반환함
    • 사용법: array.reduce(callback [, initialValue])
    • callback: 매개변수가 4가지가 있다. 순서대로 accumulator , currentValue, currentIndex(optional), array
      • accumulator : callback 의 실행 후의 반환값을 누적함, initialValue가 존재하면 처음값은 initialValue
      • currentValue : 처리할 현재 원소
      • currentIndex : 처리할 현재 원소의 인덱스, initialValue가 존재하면 0, 아니면 1부터 시작 즉  accumulator는 첫번째 원소가 되고currentValue는 2번째 원소가 됨
      • array : reduce()를 호출한 배열
    • initialValue : callback이 실행될 때 accumulator에 들어갈 초기값, 없으면 배열의 첫 원소가 됨, 즉 accumulator는 첫번째 원소가 되고currentValue는 2번째 원소가 됨. 빈배열에서 초기값 없이 reduce() 쓰면 오류발생
    • 각 배열의 원소마다 callback을 통해 계산된 값들이 누적된 값을 반환
    • Array.prototype.reduceRight() => reduce()가 왼쪽->오른쪽으로 줄인다면, reduceRight()는 오른쪽->왼쪽으로 줄인다.
      • 예시: 생각해내기 너무 귀찮아서 MDN에 나와있는 예시 그대로 가져옴
    const array1 = [1, 2, 3, 4];
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15
    
    • 자매품: Array.prototype.reduceRight()
    • 다 똑같고 reduce의 계산 순서를 거꾸로 한다.
      • 예시 없음 MDN 참고하자..

    Array.prototype.includes()
    • 배열이 특정 원소를 포함하고 있는지 판별함
    • 사용법: array.includes(valueToFind[, fromIndex])
    • valueToFind : 찾을 원소
    • fromIndex : 이 배열에서 검색을 시작할 위치
      • 음수일 경우 array.length + fromIndex 의 인덱스를 asc(오름차순)으로 검색 default는 0
    • return값 : boolean ( true / false)
    [1, 2, 3, 'asdf', 'abc', 55].includes(2); //true
    [1, 2, 3, 'asdf', 'abc', 55].includes('aa'); //false
    [1, 2, 3, 'asdf', 'abc', 55].includes(55); // true
    [1, 2, 3, 'asdf', 'abc', NaN].includes(NaN); // true
    [1, 2, 3, 'asdf', 'abc', undefined].includes(undefined); // true

    Array.prototype.find()
    • 주어진 함수에 만족하는 첫 번째 원소의 값을 반환함
    • 사용법 : array.find(callback[, thisArg])
    • callbck의 매개변수들:  
      • currentValue: 처리할 현재 원소  index: 처리할 현재 원소의 인덱스  array: map을 호출한 배열
    • thisArg: callback을 실행할 때 this로 사용하는 값
    • 일치하는 값을 찾으면 바로 반환함
    • 찾지 못했으면 undefined를 반환함
    • 배열 변경하지 않음
      • 예시는 생각하기 귀찮으니까 MDN에서 가져옴
    const array1 = [5, 12, 8, 130, 44];
    
    const found = array1.find(element => element > 10);
    
    console.log(found); // expected output: 12

    자매품 : Array.prototype.findIndex()
    • 사용법 : array.findIndex(callback[, thisArg])
    • 주어진 함수에 만족하는 첫 번째 인덱스를 반환함
    • 없으면 -1 반환
    const array1 = [5, 12, 8, 130, 44];
    
    const found = array1.findIndex(element => element > 10);
    
    console.log(found); // expected output: 1

    Array.prototype.indexOf()
    • 배열에서 지정된 원소를 찾을 수 있는 첫 번째 인덱스를 반환
    • 사용법 : array.indexOf(searchElement[, fromIndex])
    • searchElement : 찾을 원소
    • fromIndex : 이 배열에서 검색을 시작할 위치 음수면, 전체 배열에서 검색 기본값인 0과 다름 없음 
    • 없으면 -1 반환
    • === 를 이용하여 비교해서 찾음
      • 예시는 생각하기 귀찮으니까 MDN에서 가져옴
    var array = [2, 9, 9];
    array.indexOf(2);     // 0
    array.indexOf(7);     // -1
    array.indexOf(9, 2);  // 2
    array.indexOf(2, -1); // -1
    array.indexOf(2, -3); // 0

    자매품 : Array.protytype.lastIndexOf()

    사용법 : array.lastIndexOf(searchElement[, fromIndex])

    • 배열의 fromIndex부터 거꾸로 찾는다.
      • 예시는 생각하기 귀찮으니까 MDN에서 가져옴
    var array = [2, 5, 9, 2];
    array.lastIndexOf(2);     // 3
    array.lastIndexOf(7);     // -1
    array.lastIndexOf(2, 3);  // 3
    array.lastIndexOf(2, 2);  // 0
    array.lastIndexOf(2, -2); // 0
    array.lastIndexOf(2, -1); // 3

    Array.prototype.splice()
    • 배열의 기존 원소를 삭제 또는 교체하거나 새 원소를 추가하여 배열의 내용을 변경함
    • 사용법 : array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
    • start : 배열의 변경을 시작할 인덱스
      • 배열보다 크면 그냥 배열 길이로 설정됨 음수면 배열의 끝에서부터 원소를 세어나감
    • deleteCount : 제거할 원소의 수,
      • 생략하거나 값이 array.length - start 보다 크면 start부터의 모든 원소를 제거
      • 0 이하면 제거 없음, 최소한 하나의 원소 지정해야함
    • item1, item2 ... : 배열에 추가할 원소들, 없으면 splice()는 원소를 제거하기만 함
    • 반환값 : 제거한 원소를 담은 배열 -> 하나만 제거 -> 배열길이 1, 제거하지 않으면 빈 배열 반환
      • 예시는 생각하기 귀찮으니까 MDN에서 가져옴
        • 2번 인덱스에서 한 개 요소 제거하고 'trumpet' 추가 ( 'drum' 지우고 그 자리에 'trumphet' 추가 )
    var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
    var removed = myFish.splice(2, 1, 'trumpet');
    
    // myFish is ["angel", "clown", "trumpet", "sturgeon"]
    // removed is ["drum"]

     

    더더 그 밖의 함수들 .. 너무 많지만 이 아래 있는 거 정도는 정리 안해도 된다.. 

    Array.prototype.pop() / Array.prototype.push() / Array.prototype.shift()

    Array.prototype.unshift()  /  Array.prototype.sort() / Array.prototype.reverse()

    그리고 더 있지만 이 정도면 충분하다. 그래도 안된다면 MDN을 애용하자. 더 자세한 내용이 수두룩하다.

    developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array

     

    Array

    JavaScript Array 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다.

    developer.mozilla.org

    console.log('See YA! World~');

     

     

Designed by Tistory.