[JS]Array methods(map, forEach,push,concat,from)

hyeonze·2021년 12월 2일
0

Array.map()

배열을 받아 매 요소를 콜백함수에 넣고 반환값을 배열에 넣어 반환하는 메서드

const arr = [1, 2, 3];
// 화살표함수 사용
const squares = arr.map(x => x * x); // [1, 4, 9];
// function 키워드 사용
const squares = arr.map(function (x) {
    return x * x;
});

Array.forEach()

반복문 대신 사용하는 메서드
반환값이 없고 콜백함수를 탈출할때 return 사용
첫 번째 인자는 배열의 각 요소

let startWithNames = [];
let names = ['a', 'ab', 'cbb', 'ada'];

names.forEach(el => {
	if (el.startsWith('a')) {     
		startWithNames.push(el);
        } 
});
console.log(startWithNames); // [ 'a', 'ab', 'ada' ]

두 번째 인자는 index값(생략가능)

let idxOfC = -1;
let arr = ['a', 'b', 'c', 'd'];

arr.forEach((el, idx) => {
    if (el === 'c') {
	idxOfC = idx;
	return;
    }
});
console.log(idxOfC); // 2

예제

  1. moreThan100 함수를 구현해 주세요.
    숫자로 구성된 배열을 인자로 받습니다.
    100 보다 크거나 같으면, true 를
    100 보다 작으면 false 로 요소를 변경하여, 새로운 배열을 return 해주세요.
    예를 들어,

    nums(input)가
    [100, 9, 30, 7]
    이라면
    return은
    [true, false, false, false]
    
    const moreThan100 = nums => {
    let ret = nums.map(x => {
    	if (x >= 100) return (true);
    	else return (false);
    });
    return (ret);
    }
    let a = [100, 9, 30, 7];
    let b = moreThan100(a);
    console.log(b);
  2. formatDate 함수를 구현해 주세요.
    날짜가 담긴 배열을 인자로 받습니다.
    날짜의 data type은 string이며, 보내는 날짜 타입은 'YYYY-MM-DD' 입니다.
    해당 날짜의 형식을 'YYYY년 MM월 DD일' 로 바꿔서, 새로운 배열을 return 해주세요.
    예를 들어,

    dates(input)가
    ['2019-03-21', '2019-04-21', '2019-05-21']
    이라면
    
    return은
    ['2019년 03월 21일', '2019년 04월 21일', '2019년 05월 21일']
    
    let ret = dates.map(x => {
    // x = "안녕하세요";
    x = x.replace("-", "년 ");
    x = x.replace("-", "월 ");
    x = x + "일";
    return (x);
    });
    return (ret);
    }
    let d = ['2019-03-21', '2019-04-21', '2019-05-21'];
    let ret = formatDate(d);
    console.log(ret);

push와 concat

Array.push와 Array.concat모두 배열에 값을 추가하는 메서드임. 차이점은 push는 원본배열에 추가하는 것이고, concat은 원본배열에 추가하여 반환하는 점.

Array.from

내용은 같으나 주소가 다른 배열 복사

let a = [1, 2];
let b = Array.from(a);
console.log(a, b, a===b); // [1, 2], [1, 2], false
profile
Advanced thinking should be put into advanced code.

0개의 댓글