728x90
반응형

 

<script type="text/javascript">

var myTest = new Array('AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'ZZZ');

document.write(randomItem(myTest), '<br />');
document.write(randomItem(myTest), '<br />');
document.write(randomItem(myTest), '<br />');

/* 출력 결과의 예:
ZZZ
BBB
CCC
*/


// 주어진 배열에서 요소 1개를 랜덤하게 골라 반환하는 함수
function randomItem(a) {
  return a[Math.floor(Math.random() * a.length)];
}

</script>

 

 

 

예시
<body>

    <h1 id="title" style="background-color: bisque; color: snow; 
    width: 300px; height: 40px; text-align: center;"> Coding With Jina </h1>


    <script>
        const colors = ["#1abc9c", "#3498db", "#9b59b6", "#f39c12", "#e74c3c"];
        const change = document.querySelector("#title");
        
        function mouseOver(){ 
            change.style.color=randomItem(colors); 
        }
        
        change.addEventListener("mouseover", mouseOver);
        
        // 주어진 배열에서 요소 1개를 랜덤하게 골라 반환하는 함수
        function randomItem(a) {
        return a[Math.floor(Math.random() * a.length)];
        }
    </script>

 

 

결과

 

마우스를 올릴 때마다 글자색상이 바뀐다!

728x90
반응형