본문 바로가기

Study

[javascript] iterator 관련 함수

- 아래 함수들은 모두 매개변수로 callback 함수를 사용하며, callback 함수의 인수는 3개를 모두 사용하지 않아도 된다.

  (ex) numbers.forEach(function(number) {});)

 

1. forEach(callback(값, [인덱스, 배열]){})

- 배열의 길이만큼 반복하면서 각 요소에 작업을 수행할 때 사용하는 함수

- 매개변수로 callback 함수를 사용하며, callback 함수의 인수는 3개를 모두 사용하지 않아도 된다.

- return 값으로 undefined를 반환한다.

1
2
3
4
5
6
7
8
9
const fruits = ['mango''papaya''pineapple''apple'];
 
fruits.forEach(fruit => console.log('I want to eat a ' + fruit));
 
//
//I want to eat a mango
//I want to eat a papaya
//I want to eat a pineapple
//I want to eat a apple
cs

 

2. map(callback(값, [인덱스, 배열]){})

- 배열의 각 요소 값을 수정할 때 사용하는 함수

- 콜백 함수의 return 값으로 수정할 값을 보내면, return 값으로 수정된 배열을 반환한다.

1
2
3
4
5
6
const animals = ['Hen''elephant''llama''leopard''ostrich''Whale''octopus''rabbit''lion''dog'];
const secretMessage = animals.map(animal => {
  return animal.charAt(0);
});
 
console.log(secretMessage.join('')); // HelloWorld
cs

 

3. filter(callback(값,  [인덱스, 배열]{})

- 배열에서 특정조건에 맞는 값을 필터링하고자 할 때 사용하는 함수

- callback 함수의 return 값은 boolean 값(true 혹은 false)이어야 하며, 이 중 true 값이 나온 요소를 배열에 넣어 return 값으로 돌려준다.

1
2
3
4
5
6
const favoriteWords = ['nostalgia''hyperbole''fervent''esoteric''serene'];
const longFavoriteWords = favoriteWords.filter(word => {
    return word.length > 7;
});
 
console.log(longFavoriteWords);    // [ 'nostalgia', 'hyperbole', 'esoteric' ]
cs

 

4. findIndex(callback(값, [인덱스, 배열]){})

- 배열에서 특정조건에 맞는 첫번째 값의 인덱스를 가져오고자 할 때 사용하는 함수

- callback 함수의 return 값은 boolean 값이어야 하며, 이 중 처음으로 true 값이 나온 요소의 index를 return 값으로 돌려준다.

- callback 함수의 return 값 중에 true 값이 없을 경우, return 값으로 -1을 돌려준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const animals = ['hippo''tiger''lion''seal''cheetah''monkey''salamander''elephant'];
 
const foundAnimal = animals.findIndex(animal => {
    return animal === 'elephant';
});
 
const startsWithS = animals.findIndex(animal => {
    return animal.charAt(0=== 's';
})
 
console.log(foundAnimal);            // 7
console.log(animals[foundAnimal]);    // elephant
 
console.log(startsWithS);            // 3
console.log(animals[startsWithS]);    // seal
cs

 

5. reduce(callback(누적값, 현재값, 배열){}, [초기값])

- 배열의 각 요소를 callback 함수의 내용에 적용하여 누적 값을 return 하는 함수

- 초기값이 있는 경우 첫번째 누적값에 초기값, 현재 값에 배열의 첫번째 값이 적용되며,

  없는 경우 첫번째 누적값에 배열의 첫번째 값, 현재값에 배열의 두번째 값이 적용된다.

- callback 함수의 return 값에 있는 값이 누적값에 계속 누적되며, 현재값은 배열 요소값을 순차적으로 거쳐간다.

- 숫자값뿐만 아니라, 문자열도 가능하며 누적값에는 문자열이 이어진다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const newNumbers = [1357];
 
const newSum = newNumbers.reduce((accumulator, currentValue) => {
    console.log('The value of accumulator: ', accumulator);
    console.log('The value of currentValue: ', currentValue);
 
    // 로그
    // The value of accumulator:   1
    // The value of currentValue:  3
    // The value of accumulator:   4
    // The value of currentValue:  5
    // The value of accumulator:   9
    // The value of currentValue:  7
 
    return accumulator + currentValue;
});
console.log(newSum);    // 16
 
const newSum2 = newNumbers.reduce((accumulator, currentValue) => {
    console.log('The value of accumulator: ', accumulator);
    console.log('The value of currentValue: ', currentValue);
 
    // 로그
    // 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
 
    return accumulator + currentValue;
}, 10);
console.log(newSum2);    //26
cs
1
2
3
4
5
6
const cities = ['Orlando''Dubai''Edinburgh''Chennai''Accra''Denver''Eskisehir''Medellin''Yokohama'];
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");
 
console.log(word);    // CODECADEMY
cs

 

6. some(callback(값, [인덱스, 배열]))

- 배열 내에 true으로 return 되는 callback 함수의 값이 하나라도 있는지 확인하는 함수

- return 값으로 boolean형(true 혹은 false)를 리턴한다.

1
2
3
4
const words = ['unique''uncanny''pique''oxymoron''guise'];
console.log(words.some((word) => {
  return word.length < 6;
}));    // true
cs

 

7. every(callback(값, [인덱스, 배열]))
- 배열 내 모든 요소가 callback 함수의 return 값을 true로 받는 지 확인하는 함수
- return 값으로 boolean형(true 혹은 false)를 리턴한다.

1
2
3
4
const words = ['unique''uncanny''pique''oxymoron''guise'];
// 길이가 5자 이상인 단어만 골라 새로운 array 형성
const interestingWords = words.filter(word => word.length > 5);
console.log(interestingWords.every((word) => word.length > 5));    // true
cs

 

'Study' 카테고리의 다른 글

쿠키, 세션, 캐시  (0) 2020.05.25
DKIM, DMARC  (0) 2020.05.19
[javascript] 배열 관련 함수  (0) 2020.05.14
[javascript] 변수선언 방식(var, let, const)  (0) 2020.05.14
[javascript] 함수(function) 선언 방법  (0) 2020.05.13