220623.study

Universe·2022년 6월 23일
0

study

목록 보기
1/49

반복문

for (시작; 조건식; 종료식) {
    동작문;
}
조건식이 true 일 때 까지 동작문을 반복한다.

for 문과 while 문은 둘 다 같은 반복문인데 어떤 경우에 while 이 편하고 어떤 경우에 for 문이 편할까?

forwhile
구하고자 하는 값이 정확한 조건이 있는 경우에 사용구하고자 하는 값이 정확한 조건을 모를 경우, 언제끝날지 모르는 무한반복
조건식, 초기값이 함께 있어 햇갈리지 않음조건식이 흩어져 있어 가독성이 좋지않음

break;
를 사용해서 무한반복을 멈춰준다.
continue;
를 사용해서 건너뛰는 조건을 설정해준다.

중첩반복문

for (let i=0; i<10; i++){
    for(let j=0; j<10; j++){
        console.log(i,j);
    }
}

이런식으로 쓸 수 있다.
삼중 반복문도 쓸 수 있는데...
슬슬 햇갈리기 시작한다.

for(let i=0; i<5; i++){
    if(i%2 === 0) continue; // i,j,k 2로 나눈 나머지가 0 일때(0, 짝수일때) continue;
    for(let j=0; j<5; j++){
        if(j%2 === 0) continue;
        for(let k=0; k<5; k++){
            if(k%2 === 0) continue;
            
            console.log(i,j,k);
        }
    }
}

// i==0 continue;
// i==1 j==0 continue;
// i==1 j==1 k==0 continue;
// i==1 j==1 k==1 console.log(1,1,1);
// i==1 j==1 k==2 continue;
// i==1 j==1 k==3 console.log(1,1,3);
// i==1 j==1 k==4 continue;
// i==1 j==1 k==5 false;
// i==1 j==2 continue;
// i==1 j==3 k==0 continue;
// i==1 j==3 k==1 console.log(1,3,1);
// i==1 j==3 k==2 continue;
...
// i==3 j==3 k==3 console.log(3,3,3);
// i==3 j==3 k==4 continue;
// i==3 j==3 k==5 false;
// i==3 j==4 continue;
// i==3 j==5 false;
// i==4 continue;
// i==5 false;

퀴즈

구구단을 출력하되, 짝수가 나오지 않게 하라.

for(let i=1; i<10; i++){
    for(let j=1; j<10; j++){
        if(i*j % 2 === 0) continue; // 곱한 값이 홀수라면 곱하는 값도 항상 홀수이다.
        console.log(i+"X"+j+"="+i*j);
    }
}


별찍기

사용한 새로운 명령어

String newString repeat(Integer count)
string.repeat(count)
문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환한다.

*
**
***
****
*****
for(let i=1; i<6; i++){
    console.log('*'.repeat(i));
}
*****
****
***
**
*
for(let i=5; i>0; i--){
    console.log('*'.repeat(i));
}

만약 i = 0 을 고집하고 싶다면 ?

for(let i=0; i<5; i++){
    console.log('*'.repeat(5-i));
}

난이도 중

*
***
*****
*******
*********

for(let i=1; i<10; i+=2){
    console.log('*'.repeat(i));
}
*********
*******
*****
***
*
for(let i=0; i<10; i+=2){
    console.log('*'.repeat(9-i));
}

난이도 상

힌트 : console.log(' '.repeat(?) + '*'.repeat(?))


*****
 ****
  ***
   **
    *
console.log(' '.repeat(0) + '*'.repeat(5))
console.log(' '.repeat(1) + '*'.repeat(4))
console.log(' '.repeat(2) + '*'.repeat(3))
console.log(' '.repeat(3) + '*'.repeat(2))
console.log(' '.repeat(4) + '*'.repeat(1))

for(i=0; i<5; i++){
    console.log(' '.repeat(i) + '*'.repeat(5-i))
}

    *
   **
  ***
 ****
*****
console.log(' '.repeat(4) + '*'.repeat(1))
console.log(' '.repeat(3) + '*'.repeat(2))
console.log(' '.repeat(2) + '*'.repeat(3))
console.log(' '.repeat(1) + '*'.repeat(4))
console.log(' '.repeat(0) + '*'.repeat(5))
for(i=1; i<6; i++){
    console.log(' '.repeat(5-i)+'*'.repeat(i));
}

난이도 최상

  *
 ***
*****
 ***
  *
  ' ' : 2 '*' :1
  ' ' : 1 '*' :3
  ' ' : 0 '*' :5
  ' ' : 1 '*' :3
  ' ' : 2 '*' :1
for(let i = 1; i <= 5; i++ ){  
  console.log(' '.repeat( 2- 5 % i ) + '*'.repeat(5 % i * 2+1))
}

마지막 문제에서 많이 헤맸다.

객체

  1. 배열
    다양한 자료형들을 하나로 묶어놓음

let fruits = ['apple', 'orenge', 'pear', 'melon']

배열 안에 배열을 넣을 수 있다.

let arrayOfArray = [[1,2,3], [4,5]];
arrayOfArray[0] = [1,2,3];

배열 내부의 든 값을 요소(element) 라고 한다.
요소의 갯수는 .length 로 구할 수 있다.

console.log(fruits.length) = 4;

이것을 이용하여 배열의 첫번째 요소와 마지막 요소의 값을 찾을 수 있다.

console.log(fruits[0]) = 'apple'
console.log(fruits[fruits.length-1]) = 'melon'

배열에 요소를 추가할 수 있다.

fruits[5] = 'peach'
fruits[fruits.length] = 'peach'

배열 맨 앞에 요소를 추가/제거할 경우 = unshift / shift
배열 맨 뒤에 요소를 추가/제거할 경우 = push / pop
배열 중간 요소를 추가/제거 =
splice(1) = 1번째 인덱스부터 전체 삭제
splice(2,2) = 2번째 인덱스부터 2개 삭제
splice(1,0,'grape') = 1번째 인덱스부터 0개 삭제 후 'grape' 요소 추가

배열에 특정 요소가 있다면 true, 없다면 false = includes
let Juice = fruits.includes('orenge');
console.log(Juice);
true

(앞에서부터) indexOf / (뒤에서부터) LastIndexOf
검색하고 싶은 값이 몇번째 인덱스에 위치하는지 알 수 있다.
값이 존재하지 않으면 '-1'을 출력한다.

배열의 반복

let i=0;
while(i < fruits.length) { // length -1 까지 이므로 i < length
    console.log(fruits[i]);
    i++;
}

apple
orenge
pear
melon

퀴즈
다음 배열에서 '라'를 모두 제거하시오.
const arr = ['가', '라', '다', '라', '마', '라']

for(let i=0; i<arr.length; i++){
    if(arr[i] === '라'){
        splice(i,1);
    }
}

indexOf를 쓰지 않고도 제거할 수 있었다.



정답

let index = arr.indexOf('라');
while(index > -1){
  arr.splice(index, 1);
  index = arr.indexOf('라');
}

흠..
어떤게 더 효율적인 코드인지는 아직 잘 모르겠다.
저렇게 쓰는 이유가 있을 것 같은데

profile
Always, we are friend 🧡

0개의 댓글