728x90
반응형
1. forEach()
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
for문과 비슷하게 유명한 배열 메서드이다.
단, 배열 전체 값을 순회하지만 콜백 함수의 반환 값은 무시한다.
2. every()
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
배열 끝까지 또는 콜백 함수가 false를 반환할 때까지 순회한다.
3. some()
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
배열 끝까지 또는 콜백 함수가 true를 반환할 때까지 순회한다.
빈 배열에서 호출할 경우 무조건 false을 반환합니다.
every()와 some()은 특별한 반환값 덕분에 이반적인 for 루프의 break 문처럼 끝까지 순회하기 전에 순회를 끝내는데 쓰인다.
every()는 배열의 모든 요소가 조건에 충족한지 확인할 때 사용하자.
some()은 배열의 1개의 요소라도 특정 조건에 충족하는지 확인할 때 사용하면 된다.
728x90
반응형
'Language > JavaScript' 카테고리의 다른 글
[JS] FormData를 이용한 Local 이미지(+ file) Axios로 전송하기 (0) | 2022.11.22 |
---|---|
[JS] console.log [Object] 출력하기 + JSON.stringity() (0) | 2022.11.16 |
[JS] == vs. === JavaScript 개발자라면 알아야 하는 개념 (0) | 2022.10.07 |
[JS] 자네, 두 Array를 비교하고 싶지 않은가? feat.객체 비교하는 법 (0) | 2022.10.06 |
[JS] forEach에서 비동기 함수 사용 금지! (0) | 2022.09.29 |
댓글