Today I Learned
반복에 사용하는 함수 ( while/do~while/for/array.foreach() )
리꾸엘메
2022. 3. 16. 17:53
1. while
조건이 참일 때 계속 반복한다. 조건이 거짓이면 넘어간다.
statement를 여러개 사용하려면 { } 를 써야 한다.
while (condition)
{statement}
2. do~while
실행 먼저 되고 조건이 참인지 확인한다. (무조건 한 번은 실행됨)
do{
statement} while (condition)
3. for
for는 반복횟수를 정하는 경우에 사용한다.
for(initialization; condition; final-expression) {
statement }
- initialization : 카운트할 변수 선언, let은 지역변수, var는 for문과 같은 범위
- condition: 매번 반복할 때마다의 조건, 참이면 statement를 반복, 거짓이면 다음식으로 넘어감
- final-expression: 매번 반복이 끝난 후의 동작(주로 카운트 변수 증감)
4. array.foreach()
for를 foreach로 대체할 수 있다.
각 배열의 요소를 한 번씩 실행한다. (중간에 그만할 수 없다. )
array.foreach((element) => 동작 (element))
5. for ...of
반복할 수 있는 모든 객체를 반복한다.
반복가능한 객체는 ? : array, map, set, string, typedarray, argument(전달인자-값:매개변수에 들어가는 인자)
let iterable = [10, 20, 30]
for (variable of iterable) {
statement}
iterable은 반복가능한 속성이 있는 객체 (array, map, set, string, typedarray, argument 등)
variable은 속성값 ( a 든 뭐든 반복할 수 있는 무엇의 속성값을 지정하면 된다. 1, 2, 3 이라면 num 이런 식으로)
6. 이 외에 반복에 사용하는 함수들
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every( (element) => element < 40 ))
// 출력: true ( true, false 로 모든 요소가 조건을 충족하는지 알려준다. )
console.log(array1.some((element) => element > 35 ))
// 출력: true ( true, false 로 조건을 충족하는 요소가 있는지 알려준다. )
console.log(array1.find((element) => element < 40 ))
// 출력: 1 ( 조건을 만족하는 첫번째 값을 반환한다. 없다면 undifined )
console.log(array1.findIndex((element) => element < 40 ))
// 출력: 0 ( 조건을 만족하는 첫번째 요소의 인덱스를 반환한다. 없다면 -1을 반환한다. )