iterator(반복자)

장돌뱅이 ·2022년 1월 10일
0

JavaScript

목록 보기
18/46

자바스크립트에 빌트인되어있는 배열 메서드를 반복 메서드(iteration methods) 혹은 반복자라고 부른다. 반복자는 요소를 조작하고 값을 반환하기 위해 배열에서 호출되는 메서드다.

  • .forEach() 메서드
    배열의 각 요소에 대해 콜백함수를 한번씩 호출하는 메서드.
    콜백 함수는 인수로서 다른 함수에 전달되는 함수다.
    반환값은 항상 undefined 이다.
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// 기본 작성법
fruits.forEach(function(fruitsItem) {   //fruits가 식별자가 된다. 
  console.log(fruitsItem);
});

//화살표함수 작성법 **주로 씀**
fruits.forEach(fruitsItem => 
console.log(fruitsItem));

//함수선언식 작성법
function printFruit(element) {
  console.log(element);
}

fruits.forEach(printFruit);
//
mango
papaya
pineapple
apple  동일값 반환
  • .map() 메서드
    배열 내 각각의 요소에 대하여 (콜백)함수 호출 결과를 모아 새로운 배열을 반환한다.(본래 배열은 변경되지 않는다.)
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

const secretMessage = animals.map(letter => {
  return letter[0];
});

console.log(secretMessage.join(''));
//HelloWorld 반환
const bigNumbers = [100, 200, 300, 400, 500];

const smallNumbers = bigNumbers.map(divide => {
  return divide/100;
})
console.log(smallNumbers);
//[ 1, 2, 3, 4, 5 ] 반환 
  • .filter() 메서드
    배열 내의 요소들을 특정 조건에 따라 필터링한 후 결과값으로 새로운 배열을 반환한다.
    .filter 메서드에 사용되는 콜백함수는 반드시 true나 false값을 반환해야 한다.
    원본 배열값이 콜백함수를 통과한 결과가 true일 경우에만 그 값이 새 배열에 저장된다.
const randomNumbers = [375, 200, 3.14, 7, 13, 852];

const smallNumbers = randomNumbers.filter(number => {
  return number < 250;
})
console.log(smallNumbers);
//[ 200, 3.14, 7, 13 ]반환
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];

const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;
})

console.log(longFavoriteWords);
// [ 'nostalgia', 'hyperbole', 'esoteric' ]반환
  • .findIndex() 메서드
    주어진 콜백함수에 의해 true로 판명되는 배열 내 최초요소의 인덱스 값을 반환한다.
    만족하는 조건의 값이 없을 경우 -1 반환.
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {
  return animal === 'elephant';
});
console.log(foundAnimal); //7반환
const startsWithS = animals.findIndex(withS => {
  return withS[0] === 's';
})

console.log(startsWithS); //3반환
  • .reduce() 메서드
    배열 각 요소에 대해 주어진 콜백함수를 실행하여 '하나의 결과값'을 반환한다.(배열을 점점 줄여나간다. 누적식.)
const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10); // <-- .reduce() 메서드는 두번째 매개변수로 초기값을 설정할 수 있다.(옵션값)

console.log(newSum);
//
The value of accumulator:  10
The value of currentValue:  1
The value of accumulator:  11
The value of currentValue:  3
The value of accumulator:  14
The value of currentValue:  5
The value of accumulator:  19
The value of currentValue:  7
26 반환

** 참고 (동일한 반복자 작성법)

const newSum = newNumbers.reduce(function(accumulator, currentValue){
  // Existing code...
}, 10)
const newSum = newNumbers.reduce((accumulator, currentValue) => {
  // Existing code...
}, 10)

이외에도 다양게 빌트인되어 있는 배열메서드가 있다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods 참조
-간단한 정의
-메서드를 사용하는 올바른 문법
-메서드가 요구하는 매개변수 리스트
-함수의 반환값
-좀 더 긴 설명
-메서드 사용 예제
-추가적 정보 등을 담고 있다.

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

console.log(words.some((word) => {
  return word.length < 6;
})); // true반환 (배열의 요소 중 하나라도 조건을 만족할 경우 true)

const interestingWords = words.filter((word) => {
  return word.length > 5; 
});

console.log(interestingWords);  //['unique', 'uncanny', 'oxymoron']반환


console.log(interestingWords.every((word) => { 
  return word.length > 5;
} )); // // true반환 (배열의 모든 요소가 조건을 만족할 경우 true)

0개의 댓글

관련 채용 정보