JS | Iterators

yeeun lee·2020년 7월 1일
0

Javascript

목록 보기
3/4

네이버 블로그에 업로드했었던 자바스크립트 정리 내용을 이사하는 중 🙂 local document에만 저장하고 블로그에 올리지 않았어서 내용이 생각보다 많지는 않다.

codecademy에서 강의를 듣는 중 기초 강의 치고 다른 강의보다 실용적이고, 최신 버전의 syntax들을 알려줘서 좋은 것 같다.

어쨌든 나름 순항하고 있었는데, 반복자iterator가 생소한 개념이라 이해하는데 시간이 오래 걸려 복습을 위해 정리해보았다.

Higher function

  • 자바스크립트 함수는 일급 객체여서 property와 method를 가진다.
  • functions as parameter = callback function

Concept of iterator built-in javascript array method

  • for, loop를 통해 배열 안에 있는 요소element를 체크할 수 있지만, 더 쉽게 하는게 반복 메소드iteration method !
  • 콜백 함수를 취한다 callback function * functions as parameter = callback function
Fruits = ['mango', 'papaya', 'pineapple', ‘apple’] 

//array.forEach(변수 => 코드블록) 
fruits.forEach(item => console.log(item));

//array.forEach(function(변수) { 코드블록 } )
fruits.forEach(function(item) {console.log(item);}

.forEach()

  • 배열의 각 요소에 대해 같은 코드를 실행한다.
  • 실행 시 배열을 바꾸지 않고, return에 대해 undefined를 반환한다.

.map()

  • forEach 와 동일하게 배열의 각 요소에 대해 같은 코드를 실행한다.
  • 다른 점은 return에 대해 same size, but updated 요소로 구성된 새로운 배열을 반환한다는 점!

*** Difference between forEach & map method

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

let arr = [ 1 , 2 , 3 , 4 ] /* arr 라는 배열이 있다고 가정해보자.
이때 새롭게 정의한 arr2 를 콘솔에 부른다면 반환 값은 */
arr2 = arr.forEach ( num => { return num * 2 } )
console.log(arr2) //output : undefined

arr2 = arr.map ( num => { return num * 2 } )
console.log(arr2) //output : [ 2 , 4 , 6 , 8 ]

*** Key takeaways

  • forEach 로 할 수 있는 것들은 map 으로 가능. 반대도 성립
  • map은 메모리를 할당하고 return value를 저장할 수 있지만, forEach는 return value를 버리고 항상 undefined 를 반환한다.
  • foreach 는 콜백 함수가 최근 배열을 바꾸는 것을 하락하지만, map은 새로운 배열을 반환함. -> 내가 했을 때는 배열이 안 바뀌는데... 무엇을 말하는지 잘 모르겠음

.filter()

  • 기존 배열에서 코드블럭{}의 조건을 만족하는(meets certain criteria) 요소들을 새로운 배열에 반환한다.
  • 코드 블럭의 조건은 true or false 로 구분되는 조건이어야 한다!
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(numbers => {
  return numbers < 250 
})
console.log(smallNumbers) /// output: [ 200, 3.14, 7, 13 ]

.findIndex()

  • filter와 동일하게 기존 배열에서 코드블럭의 조건을 만족하는 요소를 찾으나, 반환 값은 첫 번째 요소의 index !
  • 모든 요소들이 조건을 만족하지 않을 경우, -1 을 반환한다.
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const startsWithS = animals.findIndex (animal => { 
  return animal.charAt(0) === 's'}) 

console.log(startsWithS) // output: 3  (element의 0번째 character가 s인 index를 반환)

.ruduce

  • 배열 내 요소를 반복 후 하나의 value를 반환한다.
  • 콜백함수의 initial value 를 설정하기 위해서 선택적으로 두 번째 paramter를 가질 수 있다.
const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
})
console.log(summedNums) // output: 17
profile
이사간 블로그: yenilee.github.io

0개의 댓글