My Boundary As Much As I Experienced

JS) some, every, find 본문

FrontEnd/Javascript(Vanilla)

JS) some, every, find

Bumang 2023. 8. 28. 09:49

some

리턴 값이 하나라도 true라면 true값 반환.

(빈 배열에서 사용하면 false값 반환)

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

 

 

 

every 

모든 인자들이 콜백함수 테스트를 통과하면 true를 반환. 콜백함수를 하나라도 통과하지 못할 시 false 반환.

every함수와 부정연산자(!)를 사용하여 콜백을 짜면 하나라도 참일 시 false를 반환하는 로직을 짤 수 있다.

(빈 배열에서 사용하면 true값 반환)

const isBelowThreshold = (cur) => cur < 40;

const array1 = [1, 30, 39, 29, 10, 13];
const array2 - [1, 2, 5, 12, 36, 42];

console.log(array1.every(isBelowThreshold));
// expected output: true

console.log(array2.every(isBelowThreshold)
// expected output: false

 

 

 

find

해당 콜백함수를 충족하는 가장 첫 번째 값을 반환. filter와 비슷하지만 단 하나만 찾아준다는게 특징.

중복이 없고 고유성이 보장되는 배열이라면 filter와 거의 같게 사용할 수 있을거 같다.

 

const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element) => element > 10);

console.log(found);
// Expected output: 12

const target = 12;
console.log(array1.find(el => 12))
// Expected output: 12