티스토리 뷰

key words

  • JS Math.floor() - 소수점을 없애기 위해 사용되는 함수 +a) Math.ceil() 소수점 올림, Math.round() 소수점 반올림 
  • JS Math.random() - 이 함수는 부동소수점을 반환하기 때문에 소수점이 존재합니다. 
  • JS 재귀(recursion)함수 - 함수 내부에 자기 자신을 호출하는 함수 
  • CSS 템플릿 레터럴 ``(백틱)
  • CSS linear-gradient()함수 - 색상에 그라데이션을 주는 기능

linear-gradient() 설명 MDN▼

https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient() 

 

linear-gradient() - CSS: Cascading Style Sheets | MDN

The linear-gradient() CSS function creates an image consisting of a progressive transition between two or more colors along a straight line. Its result is an object of the <gradient> data type, which is a special kind of <image>.

developer.mozilla.org

이슈: 색상 두가지를 뽑아서 배경색상에 그라이데이션을 줄 때, 만약에 a와b 색상이 같을 때, 이를 방지하려면 어떻게 해야할까? -> 여기서 재귀함수를 쓰면 됩니다.

 

※주의 :

재귀함수는 메모리를 많이 차지하고 성능이 반복문에 비해 느립니다(속도 측면에서 반복문> 재귀함수). 함수를 반복적으로 호출하므로, 스택 메모리가 커지고, 호출하는 횟수가 많아지면 스택오버플로우가 발생할 수 있다.

반면, 재귀를 사용하면 코드가 짧아지고 코드 이해도가 높아지며 유지보수에 이점이 있습니다. 

자세한 내용은 재귀와 스택을 정리해놓은 블로그 링크를 참고하세요. -> https://ko.javascript.info/recursion

 

재귀와 스택

 

ko.javascript.info

(사실 무슨 소린지 완벽하게 이해할 수가 없는데.. 그냥 이럴때는 빠르게 지나치고 나중에 또 훑는게 좋을 거 같네요. 대충 재귀함수가 내부에서 본인을 호출하는 함수 라고 생각하면 될듯)

 

아래의 코드는 완성본입니다. if 절 내부에 return onBtnClickHandler(); //자기 자신을 호출하고 있습니다.

이벤트리스너를 통해서 버튼이 클릭될 때마다 배경색을 변경하는 기능을 실행해줍니다.물론 이전에 색상을 담은 배열을 생성해주고 HTML에 있는 버튼을 쿼리셀렉터로 가져와야겠죠?

function onbtnClickHandler(){
    const firstColor =  colors[Math.floor(Math.random() * colors.length)];
    const secondColor =  colors[Math.floor(Math.random() * colors.length)];
    //두 색상의 중복을 방지하기 위한 if문
    if( firstColor === secondColor) {
      return onbtnClickHandler();
    }
    document.body.style.background = `linear-gradient(.25turn,${firstColor}, ${secondColor})`
  
}


button.addEventListener("click", onbtnClickHandler);

 

댓글