
알고있으면 좋은 Javascript Tip✨
map()
- 배열을 순회하며 요소마다 callback 함수 적용 후 새로운 배열로 리턴 한다.
- 쉽게 말해, callback 함수를 각각의 요소에 대해 한번씩 순서대로 불러 그 함수의 반환값으로 새로운 배열을 생성한다.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
(1) map() 함수 문법
let items = list.map((txt, id, arr) => {
// txt : list를 순서대로 돌면서 나오는 값
console.log('txt : ', txt);
// id : 방금 나온 값의 인덱스
console.log('id : ', id);
// arr : 현재 반복을 돌고 있는 배열(생략가능)
console.log('arr : ', arr);
// items = return text + id로 만들어진 배열
return txt + id;
});
console.log(items);
- currentValue : 처리할 현재 요소
- index : 처리할 현재 요소의 인덱스
- array : map()를 호출한 배열
- thisArg : callback을 실행할 때 this로 사용할 값
filter()
- 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환 한다.
- 쉽게 말해, true를 반환하면 요소를 유지하고, false를 반환하면 버린다.
arr.filter(callback(element[, index[, array]])[, thisArg])
(1) filter() 함수 문법
const numbers = [1, 2, 3, 4, 5, 6];
// number : 현재 배열의 요소
// 즉 number : [1,2,3,4,5,6] 배열 형태이고 3보다 큰 수가 allNumbers에 반환된다.
const allNumbers = numbers.filter(number => number > 3);
const withNumbers = numbers.filter(number => number !== 3);
// 4, 5, 6
console.log(allNumbers);
// 1, 2, 4, 5, 6
console.log(withNumbers);
- element : 처리할 현재 요소
- index : 처리할 현재 요소의 인덱스
- array : filter()를 호출한 배열
- thisArg : callback을 실행할 때 this로 사용할 값
'Study > JavaScript' 카테고리의 다른 글
| [JS] draggable 구현하기 (0) | 2023.09.06 |
|---|---|
| [JS] Spread Operator (전개 연산자) (0) | 2023.09.04 |
| [JS] 비교 연산자 (== , !== , === , !===) (0) | 2023.09.04 |
| [JS] 논리 연산자(&&, ||) (0) | 2023.09.04 |
| [JS] 콜백 함수 (Callback Function) (0) | 2023.09.01 |