티스토리 뷰

var numbers = [3, 56, 2, 48, 5];

//Map -Create a new array by doing something with each item in an array.
console.log(numbers.map((number) => number * 2));
/* 
배열 요소 하나하나씩 돌면서 2로 곱한 새로운 배열을 반환
[6, 112, 4, 96, 10]
*/

//Filter - Create a new array by keeping the items that return true.
console.log(numbers.filter((number) => number > 10));
/* 
배열 요소 하나하나씩 검사해서 10이상인 요소만 넣은 새로운 배열을 반환
[56, 48]
*/

//Reduce - Accumulate(모으다, 누적시키다) a value by doing something to each item in an array.
console.log(
  numbers.reduce((accumulater, currentValue) => {
    console.log(`${accumulater}, ${currentValue}`);
    return accumulater + currentValue;
  })
);
/* 
reduce(함수)
       必
함수(누적값, 현재값) => { ... }
       必     必
3, 56 
59, 2 
61, 48
109, 5

114

*/

console.log(
  numbers.reduce((accumulater, currentValue, index, thisArray) => {
    console.log(`${accumulater}, ${currentValue}, ${index}, ${thisArray}`);
    return accumulater + currentValue;
  }, 9)
);
/* 
reduce(함수, 시작값)
       必
함수(누적값, 현재값, 현재인덱스, 원래배열) => { ... }
       必     必
9, 3, 0, 3,56,2,48,5
12, 56, 1, 3,56,2,48,5 
68, 2, 2, 3,56,2,48,5 
70, 48, 3, 3,56,2,48,5 
118, 5, 4, 3,56,2,48,5 

123

console.log(numbers === thisArray) // true
*/

//Find - find the first item that matches from an array.
console.log(numbers.find(number => number > 10));
/* 
배열을 하나하나씩 돌다가 조건을 만족하는 첫번째 요소를 리턴
56 
*/

//FindIndex - find the index of the first item that matches.
console.log(numbers.findIndex(number => number > 10));
/* 
배열을 하나하나씩 돌다가 조건을 만족하는 첫번째 요소의 인덱스를 리턴
1
*/

'code > javascript' 카테고리의 다른 글

Destructuring assignment  (0) 2021.05.30
Variables scope in if/else statement and for/while loop  (0) 2021.05.14
화살표 함수  (0) 2021.05.11
What is an API?  (0) 2021.05.07
what is a prototype?  (0) 2021.05.04