NOTICE

이미지 랜덤하게 보여 주기

Date : 2010. 7. 9. 17:10 Category : Programming/Javascript
[이미지명이 숫자로 순차적으로 올라가는 경우]
[code]<script>
var Num = Math.round(Math.random()*2);
document.write("<img src='이미지" + Num + ".gif' />");
</script>[/code]

그냥 random()*2 이 부분을 보시면 숫자 2가 범위에 속합니다.
실제로 그러면 이미지가

이미지0.gif
이미지1.gif
이미지2.gif

이렇게 총 세 개가 있으면 됩니다.
이미지명이 1부터 시작해서 3번까지 있다고 하면

Math.round(Math.random()*2+1);

이렇게만 해 주시면 됩니다.





[이미지명이 뒤죽박죽인 경우]
[code]<script>
var IMG = new Array("http://static.naver.com/newscast/2010/0709/1136071850877058.jpg", "http://static.naver.com/newscast/2010/0709/125427-146024526.jpg", "http://static.naver.com/newscast/2010/0708/221319-1057679648.jpg");
var Num = Math.round(Math.random()*2);

document.write("<img src='" + IMG[Num] + "' />");
</script>[/code]

배열은 0부터 시작입니다.
그러니까 Num에서 오는 값이 0에서부터 2까지니까 0, 1, 2 총 세 가지
IMG[0]은 http://static.naver.com/newscast/2010/0709/1136071850877058.jpg


var IMG ~~~~ 저 부분이 드러워 보이면

var IMG = new Array();
IMG[0] = "http://static.naver.com/newscast/2010/0709/1136071850877058.jpg";
IMG[1] = "http://static.naver.com/newscast/2010/0709/125427-146024526.jpg";
IMG[2] = "http://static.naver.com/newscast/2010/0708/221319-1057679648.jpg";


이렇게 하시면 됩니다.