기본정리 - Javascript(3)

given·2024년 10월 23일
1

FE-기본

목록 보기
8/14
post-thumbnail

Javascript 기본

1. 반복문

지정한 조건이 참(true)으로 평가되는 동안 지정된 블록문을 반복 실행할 때 사용하는 문법

1. do..while

do 부분을 먼저 실해하고 반복 여부를 평가

let count =1;
do{
	// 반복 로직
	count += 1
	console.log(count)
}while(조건문); // <-  이곳이 true일 동안 반복문 실행

2. while

반복여부를 평가하고 코드 블럭({}) 실행

let count = 1;
while(조건문){ // <-  이곳이 true일 동안 반복문 실행
	// 반복 로직
	count += 1;
	console.log(count)
}

3. for

for(let count = 1; count < 10; count++;){ // for(초깃값; 조건식; 증감식;)
	// 반복 로직
	console.log(count)
}

4. for...in

배열 → 인덱스(index), 객체 → key

const strArr = ["A","B","C","D"];

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

for (let index in strArr) {
  console.log(index);
}

const obj = {
	name: 'test',
	age: 12
}

for(let key in obj){
	console.log(key);
	console.log(obj[key]);
}

5. for...of

배열 → 값(value), 객체 → X

const strArr = ["A","B","C","D"];

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

for (let value of strArr) {
  console.log(value);
}

// 객체는 안됨 iterable <- 반복적인 속성이 아니기 때문

2. 주의 사항

⚠️ 무한 반복문(infinity loop) 반복문 안에 조건이 영구적 true일 경우

⚠️ 유사 배열 객체(레퍼객체) → 배열은 아니고 객체인데, 배열처럼 보이는 것

3. break, continue

1. continue

반복을 건너 뛰게 함

let i = 0;
while(i < 5){
	i++;
	if(i == 2) continue;
	console.log(i)
}
// 출력
// 1
// 3
// 4
// 5

2. break

반복문을 종료

let i = 0;
while (i < 5) {
  i++;
  if (i == 3) break;
  console.log(i);
}
// 출력
// 1
// 2

4. 다중 반복문 → 반복 중첩

이중 반복문 또는 다중 반복문

for (let i = 0; i < 2; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(`i: ${i}, j: ${j}`);
  }
}
// 출력
// i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// i: 1, j: 0
// i: 1, j: 1
// i: 1, j: 2

// continue는 자신과 같은 스코프에만 영향을 준다.

for (let i = 0; i < 2; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 2) continue;
    console.log(`i: ${i}, j: ${j}`);
  }
}
// 출력
// i: 0, j: 0
// i: 0, j: 1
// i: 1, j: 0
// i: 1, j: 1

for (let i = 0; i < 2; i++) {
  console.log(`i: ${i}`);
  for (let j = 0; j < 3; j++) {
    if (j === 1) break;
    console.log(`j: ${j}`);
  }
}
// 출력
// i: 0
// j: 0
// i: 1
// j: 0

PS. 요즘 코테 알고리즘은 빅오(Big-O) 표기법으로 복잡도를 계산

https://jsbench.me/ ← 로직 속도

profile
osanThor⚡️블로그 이전했습니다. https://blog.given-log.com

0개의 댓글