(underscore.js)_.contains() 함수

호두파파·2021년 2월 20일
0

underScore.js

목록 보기
4/9

_.contains() 함수

_.contains(list, value, [fromIndex])
  • list : collection으로서, 배열이나 객체가 될 수 있다.
  • value : 배열의 eleement나, 객체의 value가 될 수 있다.
  • [fromIndex] : list에서 value를 찾을 때, 찾기 시작하는 index이다 (생략 가능)

list 안에 value가 있는지 확인하고, 있다면 true를 리턴한다.

예제

_.contains([1, 2, 3], 3); // true
// 배열 [1, 2, 3]안에 3이 들어있는지 확인하고, 있으면 true를 리턴한다.

구현

  • 함수의 인자로 collection과 target을 가져온다.
  • collection은 list, target은 value를 말한다.
  • list가 배열일 경우, for 문으로 배열의 각 element가 target과 같은지 확인하고, 맞으면 true 아니면 false를 리턴한다.
  • list가 배열이 아닌 객체일 경우, for in문으로 객체의 각 value가 target과 같은지 확인하고, 맞으면 true 아니면 false를 리턴한다.
_.contains = function (collection, target) {
    // TIP: Many iteration problems can be most easily expressed in
    // terms of reduce(). Here's a freebie to demonstrate!
    if (Array.isArray(collection)) {
      for(let i = 0; i < collection.length; i++) {
        if(collection[i] === target) {
          return true
        } else {
          return false
        }
      }
    } else {
      for (let value in collection) {
        if(collection[value] === target) {
          return true
        } else {
          return false
        }
      }
    }
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글