(underscore.js) _.each

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

underScore.js

목록 보기
2/9
each _.each(list, iteratee, [context]
  • list : collection으로써, 배열이나 객체가 될 수 있다.
  • iteratee : list의 각 element(value)를 반복적으로 돌리는 함수이다.
  • [context] : iteratee 함수에서 this로 바인딩 되는 것이다. (생략 가능)

예제

  • [context]가 생략될 경우
var arr = [0, 1, 2]l
_.each(arr, function(item) {
  console.log(item); // 0, 1, 2
});

// 배열 'arr'의 각 element를 iteratee 함수인 function(item)에 인자로 반복적으로 돌려 출력값으로 나온다.
  • [context]가 입력될 경우
var arr = [0, 1, 2];
var secondArray = [4, 5, 6];
_.each(arr, function(item) {
  console.log(this[item]); //4, 5, 6
}, secondArray);

// 배열 'arr'의 각 element를 iteratee 함수인 function(item)에 인자로 반복적으로 돌리는데, 여기서 [context]인 secondArray는 iteratee 함수에 있는 this로 바인딩되어 사용된다.
// 즉, secondArray[0], secondArray[1], secondArray[2]의 값을 출력하게 되어, 4, 5, 6이 출력된다.

each 함수에서 iteratee 함수 사용시에 list가 배열이냐, 객체이냐에 따라 사용하는 인자가 다르다.

list가 배열일 경우, iteratee 함수의 인자(arguments)로 (element, index, list)를 사용한다.

var cars = [‘Tesla’, ‘Nissan’, ‘Chevy’, ‘Subaru’];
_.each(cars, function (element, index, list) {
  
  var output = ‘Element:+ element +,+ ‘Index:+ index +,+ ‘List Length:+ list.length;
console.log(output);
});
// Element: Tesla, Index: 0, List Length: 4
// Element: Nissan, Index: 1, List Length: 4
// Element: Chevy, Index: 2, List Length: 4
// Element: Subaru, Index: 3, List Length: 4

list가 객체일 경우, iteratee 함수의 인자(arguments)로 (value, key, list)를 사용한다.

var obj = {FistKey: 1, secondKey: 2};
_.each(obj, function (value, key) {
 var output = ‘The value is ‘+ value + ‘ where the key is ‘ + key;
console.log(output);
});
// The value is 1 where the key is FirstKey
// The value is 2 where the key is SecondKey

구현

알고리즘

  • 함수의 인자로 collection과 iterator를 가져온다.
  • collection이 배열일 경우, 배열의 각 element에 대해 iterator 함수를 돌리는데,
    iterator 함수의 인자는 (element, index, collection)으로 한다.
  • collecrion이 객체일 경우, 객체의 각 value에 대해 iterato 함수를 돌리는데, iterator 함수의 인자는 (value, key, collection)으로 한다.
_.each = function(collection, iterator) {
  if (Array.isArray(collection)) {
    for (var i = 0; i < collection.length; i++) {
      iterator(collection[i], i, collection);
    }
  } else {
    for (var key in collection) {
      iterator(collection[key], key, collection);
    }
  }
};
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글