프로그래밍 공부/JavaScript

[Js] - 별찍기 (콘솔)

미니미니찍찍 2021. 12. 27. 18:28

 

자바스크립트를 이용하여 콘솔에 별찍기를 작성해보았다.

for문은 익숙한 반면 forEach문은 사용할때마다 좀 헷갈리는 경우가 많아

forEach문으로도 다시 작성을 해보았다.

 

 

 

1. 삼각형찍기 

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

// 2. forEach문
const arr = ['*','*','*','*','*'];
arr.forEach(function(e,index){
    console.log(e.repeat(index + 1));
});

// 결과 
 *
 **
 ***
 ****
 *****

 

2. 삼각형 찍기 - 역순 

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

// 2. forEach문
const arr = ['*','*','*','*','*']
arr.forEach(function(e, i){
    console.log(e.repeat(5-i));
});

// 결과 
*****
****
***
**
*

3. 공백을 포함한 삼각형 

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

// 2.forEach문

['*','*','*','*','*'].forEach(function(e,i){
    console.log(' '.repeat(4 - i) + '*'.repeat(i + 1))
})

// 결과 

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

4. 공백포함한 역삼각형

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

// 2.forEach문 
['*', '*', '*', '*', '*'].forEach(function(e,i){
    console.log(' '.repeat(i) + '*'.repeat(5-i));
})

// 결과값
*****
 ****
  ***
   **
    *

5. 크리스마스 별찍기

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

// 2. forEach문

const arr = ['*','*','*','*','*','*','*','*','*']
arr.forEach(function(e,i){
    if(i % 2 !== 0){
        console.log(' '.repeat((arr.length - i)/2) + '*'.repeat(i));
    }  
})

// 결과 
    *
   ***
  *****
 *******

 

 

 

 

 

* 출처 - 제로초 유튜브 자바스크립트 별찍기 강의 참고 

728x90
반응형