본문 바로가기
Javascript

[javascript]임시 비밀번호 및 난수 생성하기 _ math.random()

by thecorative 2023. 3. 15.
반응형

배경

회사프로젝트에서 임시비밀번호와 비슷한 프로젝트를 하게 되었다. 

관리자 코드를 새롭게 임의로 생성할 수 있는 기능이다. 

이것을 통해 배운  math.random 과 math.floor 메서드에 대해서 배우게되었다. 

 

랜덤으로 숫자 생성하기 테스트 코드 작성 

먼저는 이 기능을 사용하기 위한 테스트 코드를 만들어 보았다. 

영어 대소문자 숫자 특수기호 조합으로 만드는것이다. 

    <h1>랜덤으로 숫자 생성하기</h1>
    <p id="random">코드 생성</p>
    <button onclick="generateRandomString()">생성하기</button>

    <script>
      function generateRandomString() {
        const chars =
          "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*";
        let randomStr = "";
        for (let i = 0; i < 10; i++) {
          let randomIndex = Math.floor(Math.random() * chars.length);
          randomStr += chars[randomIndex];
        }
        let random = document.getElementById("random");
        random.innerText = randomStr;

        console.log(randomStr);
      }
    </script>

 

결과

 

생성하기 클릭을 하면 임시로 생성하도록 작동이 된다. 

 

 

 0 <= random < 1 

Math.random();

Math.random() 함수는 0~1 사이의 실수를 리턴합니다.(1 미포함)

 

 

 0 <= random <= 9 

Math.floor(Math.random() * 10);

Math.random() 함수의 결과는 0~0.99999...이고,

Math.random() * 10 의 결과는 0~9.99999...입니다.

따라서, Math.floor(Math.random() * 10)의 결과는 0~9 범위의 정수입니다.

Math.random() 함수를 이용하여 정수 범위의 난수를 생성할 때는 

이렇게 Math.random() 함수를 호출한 결과를 조작하고, Math.floor()를 사용합니다.

 

 

반응형