TIL_35_with Wecode 025 javascript about array methods

JIEUN·2021년 2월 28일
0
post-thumbnail

array의 반복문으로 사용하는 map 과 forEach 메소드에 대하여.

Array.map() 이란?
map 메소드는 배열을 반복해주는데 callback 함수에서 return한 값으로 각각의 요소 하나하나를 수정해준다.

const arr = [1, 2, 3];
const squares = arr.map(x => x * x);

결과는 [1, 4, 9];

const squares = arr.map(x => x * x); 이 부분을 풀어보면면,

const squares = arr.map(function (x) { 
  return x * x;
});

Array.forEach() 란?
forEach 는 for 대신 사용하는 반복문이다.
map 메소드는 요소가 수정된 새로운 배열이 반환된다면, forEach 메소드는 아무것도 반환하지 않는다. forEach 는 단지 for문 대신 사용하는 반복 메소드 이다.

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

console.log(startWithNames); 결과는 ['a', 'ab', 'ada']
배열 names 안에서 'a'로 시작하는 문자들을 찾아준다.

let hasC = false;
let arr = ['a', 'b', 'c', 'd'];
arr.forEach(el => {
  if (el === 'c') {
    hasC = true;
    return;
  }
});

배열 arr 안에서 'c' 가 있다면, hasC = true; 결과. true.

let idxOfC = -1;
let arr = ['a', 'b', 'c', 'd'];
arr.forEach((el, idx) => {
  //두 번째 인자도 받을 수 있다.
  if (el === 'c') {
    idxOfC = idx;
    return;
  }
});

console.log(idxOfC);의 결과는 2.
arr 배열 안에서 'c'가 몇 번째 인덱스인지 확인할 수 있다.

Assignment
두 문제 모두 map 메서드와 arrow function을 사용해주세요.
1. moreThan100 함수에 숫자로 구성된 배열을 인자로 넘겨드립니다.
100 보다 크거나 같으면, true를
100 보다 작으면 false로 요소를 변경하여
새로운 배열을 return해주세요.
예를 들어

nums(input)[100, 9, 30, 7]
return[true, false, false, false]
const moreThan100 = nums => {
  let arr = nums.map (
    i => { if (i <100) {
      return false;
    }
          return true;
         }
    )
  return arr;
}

moreThan100([100, 104, 105, 90]);
결과는 [true, true, true, false]

  1. 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일']
const formatDate = dates => {
let str = dates.map (function(arr) { 
let date = arr.split('-');
console.log(`${date[0]}${date[1]}${date[2]}`)
  return `${date[0]}${date[1]}${date[2]}`;
 })
  return str;
}

0개의 댓글