![[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 26회차 미션](/assets/img/FCFE/post26.jpg)
[패스트캠퍼스 수강 후기] 프론트엔드 인강 100% 환급 챌린지 26회차 미션
2020, Nov 13
강의
23 배열 내장함수 forEach
배열 원소들 출력 시 아래와 같이 할 수 있음
const superHeros = ['ironman', 'captainAmerica', 'doctorStrange'];
for (let i = 0; i < superHeros.length; i++) {
console.log(superHeros[i]);
}
forEach
를 사용하면 아래와 같이 바꿀 수 있다.
function print(hero) {
console.log(hero);
}
superHeros.forEach(print);
이 코드를 좀 더 간단하게 하면
superHeros.forEach(function (hero) {
console.log(hero);
});
화살표 함수를 사용하면
superHeros.forEach((hero) => {
console.log(hero);
});
24 배열 내장함수 map
기존 배열의 모든 원소를 제곱한 원소를 갖는 배열을 만들어보자
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const squared = [];
for (let i = 0; i < array.length; i++) {
squared.push(array[i] * array[i]);
}
console.log(squared);
forEach
를 사용하면
array.forEach((num) => {
squared.push(num * num);
});
map
을 사용하면
const square = (n) => n * n;
const squared = array.map(square);
혹은
const squared = array.map((n) => n * n);
이렇게도 가능!
map
은 배열의 내용을 전체적으로 변환하고 싶을 때 사용하는 내장함수!
객체에서 활용해보기
const items = [
{
id: 1,
text: 'hello'
},
{
id: 2,
text: 'bye'
}
];
const texts = items.map((item) => item.text);
console.log(texts);
결과
[“hello”, “bye”]
indexOf
배열 내 항목이 몇번째 원소인지 찾는 법
const superheroes = ['아이먼맨', '캡틴아메리카', '토르', '닥터스트레인지'];
const index = superheroes.indexOf('닥터스트레인지');
console.log(index);
결과 2
findIndex
indexOf
로는…
- 객체를 찾을 수 없음
- 특정 조건으로 찾는 것이 어려움
const todos = [
{
id: 1,
text: '자바스크립트 입문',
done: true
},
{
id: 2,
text: '함수배우기',
done: true
},
{
id: 3,
text: '객체와 배열배우기',
done: true
},
{
id: 4,
text: '배열 내장함수 배우기',
done: false
}
];
const index = todos.indexOf(3);
console.log(index);
결과 -1 : 일치하는 것이 없다!!!
findIndex 를 사용해야 함!
findIndex
는 함수(조건)를 사용
const index = todos.findIndex((todo) => todo.id === 3);
console.log(index); // 2
id
값이 3인 객체의 index를 찾아서 리턴해줌!
find
찾은 객체(값) 자체를 리턴해준다. 가장 첫 번째로 찾은 원소를 알려준다.
const index = todos.find((todo) => todo.id === 3);
console.log(index);
결과
{id: 3, text: “객체와 배열배우기”, done: true}
다음과 같이 사용도 가능
const index = todos.find((todo) => todo.done === false);
26회차 인증샷
올인원 패키지 : 프론트엔드 개발👉https://bit.ly/3m0t8GM