prestudy-week2

Sunghee Kim·2022년 4월 26일
0

map()

메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Assignment

helloBot이라는 함수를 만들어주세요.
for문을 사용하여 빈 result배열에 greetings에 들어있는 인삿말을 채워주세요.
인자에는 0과 1로 이루어진 배열이 들어갑니다.

<조건문과 반복문만 썼을 경우>
let group1 = [0,1,1,0,0]
helloBot(group1); // --> ['안녕하세요','또 만나네요','또 만나네요','안녕하세요','안녕하세요']

const helloBot = people => {
let result=[];
for(let i=0;i<people.length;i++){
if(people[i]===0){
result.push('안녕하세요')
}else if(people[i]===1){
result.push('또 만나네요')
}
}
return result;

}
<map()메서드 사용하기>
const helloBot = people => {
let result=[];
people.map(p=>{
if(p===1){
result.push('또 만나네요')
}else{
result.push('안녕하세요')
}
})
return result;
}
<map()메서드와 삼항 연산자 사용하기>
const helloBot = people => {
return people.map(p=>p===1 ? '또 만나네요':'안녕하세요')
}

profile
개발하는 스트롱맘

0개의 댓글