Programming/JavaScript

[JavaScript] Loops & Iterators

inyeong 2024. 9. 28. 10:52

1. For Loop 

for 반복문은 (1) iterator 변수 초기화, (2) stopping condition, (3) iterator 변수 업데이트로 이루어진다. 

stopping condition이 참이면 블록 내부 코드가 실행되고 거짓이면 중지된다. 

for (let i=0; i<3; i++) {
	console.log(i);
}

 

for 반복문과 배열의 .lenth 속성을이용하여 배열에도 쉽게 접근할 수 있다. 

const animals = ['Dog', 'Cat', 'Bear', 'Pig'];

for (let i=0; i<animal.length; i++) {
	console.log(animals[i]);
    }

 

2. Nested Loops (중첩 반복문) 

반복문 내부에 다른 반복문이 있는 것을 중첩 반복문이라 한다. 

const myArray = [1, 2, 3];
const your Array = [4, 5, 6];

for (let i=0; i<myArray.length; i++) {
	for (let j=0; j<yourArray.length; j++) {
    	if (myArray[i] === yourArray[i]){
        	console.log(yourArray[i]);
		}
	}
}

 

3. While Loop 

while 반복문은 (1) 변수가 반복문 이전에 선언되며, 전역 스코프에 있으므로 while loop 내부에서 접근할 수 있다. 

(2) while 키워드 뒤 조건이 참일 때만 블록 내부 코드가 실행된다.

(3) iterator 변수를 업데이트하는 코드가 반드시 있어야 무한 루프에 빠지는 것을 방지할 수 있다. 

 

while 반복문은 반복 횟수를 알 수 없을 때 많이 사용된다. 

let counter = 0;

while (counter<3) {
	console.log(counter);
    counter++;
}

 

4. do ... While Loop 

do ... while은 조건 충족 여부에 관계없이 특정 코드를 한 번 실행한 뒤, 반복문을 실행한다.

let i=0;

do {
	console.log(i);	// 0, 1, 2
    i++;
} while (i<3);

 

5. break

기존 조건을 만족하지 않아도 반복문을 종료하고 싶은 경우 break 키워드를 사용할 수 있다.

추가 조건을 설정해 반복문에서 빠져나올 수 있다. 

for (let i=0; i<99; i++) {
	if (i<2) {
    	break;
    }
    console.log('Banana');
}
console.log('ORange');

 

6. Iterators

반복을 하는 데 도움을 주는 자바스크립트의 내장 배열 메소드를 iteration methods 또는 iterators라고 한다. 

iterator는 배열의 요소를 조작하고 값을 반환하기 위해 배열에서 호출되는 메소드이다. 

 

.forEach()

.forEach() 메소드는 배열의 각 요소에 대해 같은 코드를 실행한다. 

callback function(콜백 함수)을 인자로 받고, 배열의 각 요소에 대해 콜백 함수를 실행한다. 

const groceries = ['sugar','salt','walnuts'];

groceries.forEach(groceryItem => {console.log(groceryItem);});

 

.map()

.map() 메소드는 새로운 배열을 반환한다. 

배열의 각 요소가 callback function(콜백 함수)에 전달되고, .map()의 반환값이 새로운 배열에 저장된다.

const numbers = [1, 2, 3, 4, 5]; 

const bigNumbers = numbers.map(number => {return number * 10;});

console.log(numbers);	 // [1, 2, 3, 4, 5]
console.log(bigNumbers); // [10, 20, 30, 40, 50]

 

.filter()

.filter() 메소드는 배열의 특정 요소만 필터링하여 새로운 배열을 반환한다. 

배열의 각 요소가 callback function(콜백 함수)에 전달되고, 조건에 따라 true나 false를 반환한다.

이때 true를 반환한 요소들만 새로운 배열에 추가된다. 

const words = ['chair', 'music', 'pillow', 'pen', 'door'];

const shortWords = words.filter(word => {return word.length < 6;});

console.log(words);		// ['chair', 'music', 'pillow', 'pen', 'door']
console.log(shortWords);	// ['chair', 'music', 'pen', 'door']

 

.findIndex()

.findIndex() 메소드는 배열에서 특정 요소의 위치를 찾을 때 사용한다. 

배열의 각 요소가 callback function(콜백 함수)에 전달되고, 

콜백 함수에서 true 값을 갖는 첫 번째 요소의 인덱스를 반환한다. 

const numbers = [123, 25, 78, 5, 9];

const lessThanTen = numbers.findIndex(num => {return num < 10;});

console.log(lessThanTen);	// 3
console.log(numbers[3]);	// 5

 

조건을 만족하는 요소가 없으면 -1을 반환한다. 

const greaterThan1000 = numbers.findIndex(num => { return num > 1000; });

console.log(greaterThan1000); 	// -1

 

.reduce()

.reduce() 메소드는 배열의 요소를 순회한 후 단일 값을 반환하여 배열을 축소시킨다. 

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
	return accumulator + currentValue;
    });

console.log(summedNums) // 17

 

accumulator의 초기 값은 배열의 첫 번째 요소, currentValue의 초기 값은 두 번째 요소이다.

반환값(accumulator+currentValue)이 다음 반복의 accumulator가 되고, currentValue 배열의 다음 요소가 된다. 

반복 accumulator currentValue accumulator + currentValue
1 1 2 3
2 3 4 7
3 7 10 17

 

두번째 매개변수로 accumulator의 초기 값을 지정할 수도 있다.

 

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
	return accumulator + currentValue
	}, 100);

console.log(summedNums); // 117
반복 accumulator currentValue accumulator + currentValue
1 100 1 101
2 101 2 103
3 103 4 107
4 107 10 117

 

예제 코드

 

https://github.com/inyeongjang/Snoopy/blob/main/week03/6-Loops.js

 

Snoopy/week03/6-Loops.js at main · inyeongjang/Snoopy

Contribute to inyeongjang/Snoopy development by creating an account on GitHub.

github.com

 

https://github.com/inyeongjang/Snoopy/blob/main/week03/7-Iterators.js

 

Snoopy/week03/7-Iterators.js at main · inyeongjang/Snoopy

Contribute to inyeongjang/Snoopy development by creating an account on GitHub.

github.com

 

출처/참고자료 https://www.codecademy.com/enrolled/courses/introduction-to-javascript

 

Learn JavaScript | Codecademy

Begin your web development journey with our JavaScript course. Explore dynamic scripting for interactive web solutions.

www.codecademy.com