728x90

배열이 특정 조건을 만족하는지 확인하고자 하는 경우가 있습니다. 이때 사용하는 함수에는 every()와 some()이 있습니다.

 

Array.every()

Array.every()

array.every(callbackFunction(currentValue, index, array), thisArg)
  • currentValue : 배열의 현재 값
  • index : 배열의 현재 값의 인덱스
  • array : 현재 배열

every() 메서드는 배열의 모든 요소특정 조건만족하면 true하나라도 불만족한다면 false를 반환합니다.

const num = [1,2,3,4,5,6,7,8,9,10]

const even = num.every((el) => el % 2 == 0);

console.log(even); // 결과 : false

const num2 = [2,4,6,8,10];

const even2 = num2.every((el) => el % 2 == 0);

console.log(even2); // 결과 : true

 

Array.some()

Array.some()

array.some(callbackFunction(currentValue, index, array), thisArg)
  • currentValue : 배열의 현재 값
  • index : 배열의 현재 값의 인덱스
  • array : 현재 배열

some() 메서드는 배열의 모든 요소 중 단 하나 이상의 원소조건을 만족하면 true모든 요소를 불만족한다면 false를 반환합니다.

 

const num = [1,2,3,4,5,6,7,8,9,10];

const even = num.some((el) => el % 2 == 0);

console.log(even); // 결과 : true

const num2 = [1,3,5];

const even2 = num2.some((el) => el % 2 == 0);

console.log(even2); // 결과 : false

 

 

every(), some()의 차이점

every()와 some()의 차이점을 정리하자면 

 

  • every() 함수모든 요소에 대해서 조건을 만족하면 true를 반환
  • some() 함수 1개 요소만 만족해도 true를 반환
  • some() 함수는 배열의 요소 중 조건을 만족하는 요소를 만나면 그 이후 요소들을 체크하지 않고 return합니다.
  • every() 함수배열의 요소 중 조건을 불만족하는 요소를 만나면 그 이후 요소들을 체크하지 않고 return 합니다.