Please Enable JavaScript!
Gon[ Enable JavaScript ]

Javascript 에서 랜덤으로 배너를 출력하고 싶을 때

웹 프로그래밍/자바스크립트
반응형

Javascript 에서 랜덤으로 배너를 출력하고 싶을 때


사용하는 배너의 수가 M 개이고 화면에 출력하고자하는 개수가 N 개 일 때

Javascript 로 랜덤하게 N 개를 추출하여 화면에 뿌리고 싶을때가 있다.

 

getRand 함수에 파라미터로 출력하고자 하는 글의 수를 넘긴다. 그러면 그중

랜덤하게 숫자를 추출해서 넘길것이고 그 번호가 배열번호가 된다.

그것을 bottomBarAds 함수에서 다섯번 for 문을 돌면서 표현하고 있다.

 

<script language="JavaScript">

function getRand(n) {

             var r = Math.round(Math.random()*n-0.5);

             if ( r < 0 ) { r=0; } return r;

}

var adBtns = new Array(

// Button1

'<font size=+2 color=blue>1</font>',

// Button2

'<font size=+2 color=green>2</font>',

// Button3 '

<font size=+2 color=yellow>3</font>',

// Button4

'<font size=+2 color=red>4</font>',

// Button5

'<font size=+2 color=gray>5</font>',

// Button6

'<font size=+2 color=cyan>6</font>',

// Button7

'<font size=+2 color=magenta>7</font>',

// Button8

'<font size=+2 color=black>8</font>',

// Button9

'<font size=+2 color=teal>9</font>',

// Button10

'<font size=+2 color=pink>0</font>' );

 

function bottomBarAds() {

             var i, k, f = 0;

             document.write('<hr><table border="1" width="100%"><tr>');

             for ( i=0; i<5; ) {

                           k = getRand(adBtns.length);

                           if ( ! (f & (1<<k)) ) {

                                        f |= 1<<k; i++;

                                        document.write('<td align="center">'+adBtns[k]+'</td>');

                           }

             }

             document.write('</tr></table>');

}

</script>

...

<script language=javascript> 

             bottomBarAds();

</script>

반응형
Posted by 녹두장군1
,