[자바스크립트] javascript some() 사용하기
자바스크립트에서 for문의 남용을 막기위해 만들어낸 배열함수!
배열 요소 중, 조건에 만족하는 요소가 최소 하나라도 있는지 검사하는 메소드! (every() 와 반대되는 접근방식)
결과값은 true or false 로 반환한다!
[사용법]
//화살표 함수 표기법
array.some((element, index, array) => { ... });
//콜백함수로 호출하는 법
array.some(callbackFn, thisArg);
//익명함수로 표기법
array.some(function(element, index, array) {
}, thisArg);
[간단설명]
array.some() 은 배열을 순환하면서,
콜백함수의 조건에 "true" 인 요소가 하나라도 있다면 true, 없다면 false 를 반환한다.
[특징]
- 배열을 순환하면서 조건에 맞는 요소를 찾는 순간, 순환을 멈추고 즉시 true 를 반환한다.
- some() 자체는 원본배열을 변형시키지 않는다.
- 값이 존재하지 않거나, delete 된 요소는 테스트하지 않는다.
[주의]
- 빈 배열에 some() 을 사용한 경우, 무조건적으로 false 를 반환한다.
파라미터(parameter) :
callback함수 :
배열의 모든 요소를 test 할 함수. 조건에 "true" 인 요소가 있는지 검사한다
element :
(순환 중) 현재 처리중인 요소 그 자체
index (optional) :
(순환 중) 현재 처리중인 요소의 index
array (optional) :
some() 이 실행되고 있는 원본배열
thisArg (optional) :
callback 함수가 실행중일 때 this로 사용될 값
[예제1]
var array = [13, 96, 27, 38, 328, 45];
//화살표 함수
array.some(el => el < 10);
array.some(el => el > 300);
//결과값 : false
//결과값 : true
[예제2]
var champions = ['Chelsea', 'Liverpool', 'Real Madrid', 'Barcelona', 'PSG', 'Juventus'];
//함수 내에서 some() 을 사용
function checkTrophy(arr, team) {
return arr.some(el => el == team);
}
//함수를 호출
checkTrophy(champions, 'LiverPool'); //true
checkTrophy(champions, 'Spurs'); //false
//hopes for next season...
//사실 여기서는 includes() 를 사용하면 더 편할 것 같긴함....
some()과 반대되는 접근법의 메소드
https://devinserengeti.tistory.com/23?category=901017
'[개발 공부] > [자바스크립트]' 카테고리의 다른 글
[자바스크립트] javascript forEach() 사용하기 (0) | 2022.03.04 |
---|---|
[자바스크립트] javascript every() 사용하기 (0) | 2022.02.19 |
[자바스크립트] javascript filter() 사용하기 (0) | 2022.02.17 |
[자바스크립트] javascript find() 사용하기 (0) | 2022.02.12 |
[자바스크립트] javascript map() 사용하기 (0) | 2022.02.10 |