each _.each(list, iteratee, [context]
var arr = [0, 1, 2]l
_.each(arr, function(item) {
console.log(item); // 0, 1, 2
});
// 배열 'arr'의 각 element를 iteratee 함수인 function(item)에 인자로 반복적으로 돌려 출력값으로 나온다.
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
_.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);
}
}
};