[자바스크립트 기초] Array APIs 총정리

·2022년 3월 6일
0

Java Script

목록 보기
7/8
post-thumbnail

드림코딩 자바스크립트 기초 강의를 들으며 학습한 내용을 정리해보았다.
⭐️ 재생목록 바로가기


💡 위와 같이 class 생성자 함수를 사용하여 students 라는 배열을 찍어냈다.
이를 활용하여 Array 객체의 APIs를 공부해보자!

1️⃣ find()

vs code에서 command 키 누르고 해당 연산자 클릭해서 설명 확인하기

find()

Returns the value of the first element in the array where predicate is true, and undefined

  • 콜백 함수의 값이 true인 첫번째 요소를 반환한다.

(1) student, index 인자를 받아온 결과 확인하기

⬇️ console

(2) 점수가 90점인 학생 찾기

⭐️ 화살표 함수, 리턴 한 줄 -> return 선언 생략, 중괄호 생략

⬇️ console


2️⃣ filter()

filter()

Returns the elements of an array that meet the condition specified in a callback function.

  • 콜백 함수의 조건에 맞는 요소들을 반환한다.

(1) 등록된(enrolled) 학생들로 새로운 배열 만들기


⬇️ console


3️⃣ map()

map()

Calls a defined callback function on each element of an array, and returns an array that contains the results.

The map method calls the callbackfn function one time for each element in the array.

  • 배열의 각 요소가 콜백함수를 거쳐 다른 값으로 매핑 되어(변환되어), 새로운 배열로 반환

⭐️ map()의 콜백함수의 인자는 흔히 쓰는 item, value 등 보다는 알아보기 쉬운 이름을 짓는 것이 좋음 ( ex. student )

(1) 학생들의 점수로 새로운 배열 만들기

⬇️ console

(2) 학생들의 점수를 제곱한 새로운 배열 만들기


⬇️ console


4️⃣ some(), every()

some()

Determines whether the specified callback function returns true for any element of an array.

  • 배열의 요소 중 콜백함수가 true로 리턴되는 요소가 있는지 없는지를 판별
    (하나라도 있으면 true 반환)

(1) 점수가 50점보다 낮은 학생이 있는지 확인하기

(1-1) every() 와의 비교

every()

Determines whether all the members of an array satisfy the specified test.

  • 배열의 모든 요소가 콜백함수로 true가 리턴되는지를 판별


5️⃣ reduce()

reduce()

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

  • 배열의 있는 모든 요소들을 콜백함수로 변환된 값(리턴값)으로 누적하여 반환
    원하는 시작점부터 모든 배열을 돌면서 어떤 값을 누적할 때 사용한다.

(1) prev, curr 인자를 넣고 각각 출력


⬇️ console

(2) initialValue 전달하기


⬇️ console

(3) 점수의 평균 구하기

(3-1) reduce로 점수를 누적한 값을 리턴함


⬇️ console

📝 코드 정리

(3-2) result 를 학생 수 (배열의 길이)로 나눠주기

profile
걸음마 개발 분투기

0개의 댓글