언어/JavaScript

[JavaScript]ES5와 ES6의 차이(3) - 배열 관련

GAEBAL 2022. 5. 4. 16:59
728x90

ES5와 ES6의 차이(3)

배열 관련

다양한 for문이 등장(for of문, forEach문)

  <script>
    const array = [1, 2, 3, 4, 5];
    // ES5: 배열 저장된 요소 순서대로 출력
    for (let index = 0; index < array.length; index++) {
      console.log(array[index]);
    }

    // ES6: for(item of items)
    for (item of array) {
      console.log(item);
    }

    // array: forEach(function)
    array.forEach(function(no) {
      console.log(no);
    });

    array.forEach(no => {
      console.log(no);
    });
  </script>

실행 결과

 

배열.map() 메서드

  <script>
	// ES6: 문자열을 한글자씩 "공백"구분자로 출력
    let message = "Hello VueJS"
    let message_split = "";
    for(s of message) {
      message_split += s + " ";
    }
    console.log(message, "-", message_split);

    // array 함수: map()
    console.log('--- array map() ---');
    let result1 = array.map(value => value); // 원본 배열 객체의 요소를 매핑해서 새로운 배열 객체 복사
    console.log("array 원본: ", array);
    console.log("result1 복사: ", result1);

    // 원본 배열요소 값 * 2 매핑해서 새로운 배열 복사
    let result2 = array.map(value => value * 2);
    console.log("result2 복사: ", result2);

    // 원본 배열 요소의 값이 짝수이면 짝수, 홀수이면 홀수 정보로 매핑해서 새로운 배열객체 리턴
    let result3 = array.map(value => ((value % 2) ? "홀수" : "짝수"));
    console.log("result3 = ", result3);
  </script>

실행 결과

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환함!

728x90