求一个表格的随机点名代码,用JS写

JavaScript017

求一个表格的随机点名代码,用JS写,第1张

var isRun=true

var a = ["张三","李四","王五","赵六"]

var a2 = new Array()

function action(str){

var s = document.getElementById("bt").value

if(s=="开始"){

isRun=true

run()

document.getElementById("bt").value="结束"

}else{

isRun=false

document.getElementById("bt").value="开始"

}

}

function run(){

var i = Math.floor(Math.random() * a.length+ 1)-1

document.getElementById("show").innerHTML=a[i]

if(isRun==false){

var b =true

for(var j in a2){

if(a2[j]==i){

b=false

}

}

if(b){

a2[a2.length]=i

return

}

}

setTimeout("run()",10)

}

关键是随机数的实现(伪随机)

function myRand(start, end) {

return start + Math.round((Math.random() * (end - start)))

}

这个函数可以得到start到end之间(包括start和end)的随机数,然后根据随机数去点名

<script defer="defer">

var arr=new Array("张三","李四","王二","陈一","哈哈")

var n

var num

var timer

function change(){

if(num>=0){

n=GetRnd(0,num)

alert(arr[n])

arr.splice(n,1)

num = arr.length-1

}else{

alert("点完了")

clearInterval(timer)

}

}

function start(){

num = arr.length-1

clearInterval(timer)

timer = setInterval('change()',40)

}

function GetRnd(min,max){

return parseInt(Math.random()*(max-min+1))

}

</script>

<input type="submit" name="button" id="button" value="开始点名" onclick="start()" />