[JavaScript] Array.prototype.some(), thisArg

Yeon Jeffrey Seo·2021년 12월 16일
0

JavaScript

목록 보기
2/7

some()

some() 메서드는 배열 요소들에 대해 순회하며, 콜백 함수의 조건에 하나라도 일치하는지 확인 할 때 쓸 수 있는 메서드이다.
다시 말해, 콜백 함수의 조건에 대해 배열 요소 중 하나라도 true를 반환하면 some()의 결과는 true를 반환한다.

예제

const arr = [false, false, true, false, true, false];

console.log(
  arr.some((element, index) => {
    console.log(element, index);
    return element;
  })
);

console.log(
  arr.some(function callback(element, index) {
    console.log(element, index);
    return element;
  })
);

실행 결과

활용 예시

정형적인 활용 예시는 공식 문서에 많이 정리가 되어있다.
나는 반복문에서 특정 조건이 되면 break를 걸어서 반복문을 제어해야 하는 상황이 있었다.
배열에 대해서 메서드 체인을 사용하기 위해서 forEach를 사용했지만, forEach는 break를 사용할 수 없다는 것을 알게 되었다.
따라서 some 메서드를 반복문의 제어에 사용했다.

  arr
    .sort((a, b) => b - a)    // 내림차순 정렬
    .some((element, i) => {
      if (i + 1 > element) {
        answer = i;
        return true;
      } else answer = arr.length;
    });
  • 나중에 알게 되었는데, forEach 메서드도 콜백 함수에 false를 반환하는것으로 반복문을 제어할 수 있다.
arr.forEach(element => {
  if(condition) return false;
}   

thisArg


공식문서를 보다 보면 thisArg를 종종 보게 된다. 지금까지는 대수롭지 않게 여겼는데, 이번 기회에 이게 뭔지 찾아보고 싶었다.
간단히, thisArg는 콜백 함수에서 this로 사용할 값을 지정하는 것이다.

const arr = [false, false, true, false, true, false];

console.log(
  arr.some((element, index) => {
    console.log(element, index, thisArg);
    console.log(this);
    return element;
  }, (thisArg = "This is this"))
);

console.log(
  arr.some(function (element, index) {
    console.log(element, index, thisArg);
    console.log(this);
    return element;
  }, (thisArg = "This is this"))
);

실행 결과

위 결과를 보면 콜백 함수를 어떻게 정의했느냐에 따라 다른 결과가 출력된다.
화살표 함수로 콜백을 정의할 경우, 화살표 함수의 this는 전역 객체를 가리키므로, console.log(this) 의 결과가 전역 객체를 가리키는 것을 확인할 수 있다.
함수 정의식으로 콜백을 정의할 경우, 함수 내의 this는 thisArg 인자로 넣었던 String 객체가 출력되는 것을 확인할 수 있다.
thisArg에 대해서는 알게 되었지만, 어떤 상황에서 이걸 사용할지 감이 안 잡힌다.

참고 자료

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/some

https://ktpark1651.tistory.com/215

profile
The best time to plant a tree was twenty years ago. The second best time is now.

0개의 댓글