[JS] map, filter, every

yeni·2022년 11월 8일
0

실무에서는 for문보다는 map과 filter를 더 많이 사용한다.
for문은 속도가 빠르다
map은 유지보수에 용이하다

map

map은 배열의 원소를 일괄적으로 변형시킬 때 사용한다.
배열의 내장함수 이기 때문에 사용 시 배열과 함께 사용해야한다.

map 사용방법

const classmate = ["철수","영희","훈이"]

classmate.map((item) => (item+"어린이"))
// (3)["철수어린이","영희어린이","훈이어린이"] 

classmate.map((item, index) => item + "어린이" + index)

❗️ 화살표 함수에서 소괄호 생략이 가능할까?
classmate.map( item => item +"어린이" )

  • 화살표 함수에서는 소괄호 생략이 가능하다(상황에 따라)
  • 함수의 바디안의 코드가 한줄이라면 생략 가능
  • 화살표 함수에서 중괄호와 return 사이에 아무 것도 없으면 중괄호를 소괄호로 변경하는 것이 가능하다.
classmate.map((item) => {
  return { name : el } 
});
> 생략가능
classmate.map((item) => ({ name : el }))
["철수", "영희", "훈이"].map((el) => (el + "어린이"))
//(3) ['철수어린이', '영희어린이', '훈이어린이']

["철수", "영희", "훈이"].map(el => el + "어린이")
//(3) ['철수어린이', '영희어린이', '훈이어린이']

["철수", "영희", "훈이"].map((el) => {
    return { name: el }
})
//(3) [{…}, {…}, {…}]0: {name: '철수'}1: {name: '영희'}2: {name: '훈이'}length: 3[[Prototype]]: Array(0)

["철수", "영희", "훈이"].map((el) => ({ name: el }))
//(3) [{…}, {…}, {…}]0: {name: '철수'}1: {name: '영희'}2: {name: '훈이'}length: 3[[Prototype]]: Array(0)

["철수", "영희", "훈이"].map((el) => ({ name: el }))
//(3) [{…}, {…}, {…}]

HTML과 연결하기




filter

callbackFunction의 조건에 해당하는 모든 요소가 있는 배열을 새로 생성하는 기능

사용법

const newArray = arr.filter(callbackFunction(element, index, array), thisArg);

매개변수는 callbackFunction과 thisArg
그 중 callbackFunction은 3개의 매개변수가 있다.

  • element : 요소값
  • index : 요소의 인덱스
  • array : 사용되는 배열 객체
function test(){
	const testArray = [1,2,3,4,5];
	const newArray = testArray.filter(function(element, index, array){
    console.log(element);
    console.log(index);
    console.log(array);
    });
}

결과는 아래와 같이 나온다



every

JS에서 Array객체의 멤버함수이다.
배열 안의 모든 요소가 지정한 함수 테스트의 통과여부를 확인할 때 사용한다.
Boolean값을 반환한다.

let data = [
    { name : "철수", age : 20 },
    { name : "훈이", age : 10 },
    { name : "민수", age : 16 },
    { name : "영희", age : 22 } 
]
let result = data.every( x => {
   return (x.age >= 10)
})
console.log(result)
//true
profile
차곡차곡 쌓는 몌으니 개발노트

0개의 댓글