Javascript随机数?

时间:2009-07-14 22:50:00

标签: javascript random

我有以下脚本:

Timer=0;
function countdown(auctionid){
    var auctions;
    var divs;

    Timer=Timer+1;

    if((Timer%10=="0")||(Timer=="1")){
        $.get("current.php", {
                id:auctionid
            },
            function(data){
                auctions=data.split("||");
                for(n=0;n<=auctions.length;n++){
                    if(auctions[n] != undefined){
                        divis=auctions[n].split("##");

                        $('#futu'+divis[0]).html(divis[1]);
                    }
                }
            }
        );
    }

    var cauctionid="auctionid";
    var tauctions=auctionid.split("|");
    for(i=0;i<=tauctions.length;i++){
        if(tauctions[i] != undefined){
            var dd=$('#futu'+tauctions[i]).text();
            var cdd=dd-1;
            $('#futu'+tauctions[i]).html(cdd);

            dd=dd*1000;
            dday=Math.floor(dd/(60*60*1000*24)*1)
            dhour=Math.floor(dd/(60*60*1000)*1)
            dmin=Math.floor((dd%(60*60*1000))/(60*1000)*1)
            dsec=Math.floor(((dd%(60*60*1000))%(60*1000))/1000*1)

            if(dday==0&&dhour==0&&dmin==0&&dsec==0){
                $('#Bid'+tauctions[i]).html("SOLD");
            //return
            }
            if(dhour <=9){
                dhour = "0"+dhour;
            }
            if(dmin <=9){
                dmin = "0"+dmin;
            }
            if(dsec <=9){
                dsec = "0"+dsec;
            }

            if(dd>=1000){
                var valll=dhour+":"+dmin+":"+dsec;
            }

            if(dd<1000){
                var valll="00:00:00";
            }

            $('#Bid'+tauctions[i]).html(valll);
        }
    }
    refreshID=setTimeout("countdown('"+auctionid+"')",1000);
}

在读取的行上:     如果((定时器%10 == “0”)||(定时器== “1”)){

如何制作10,一个2到12之间的随机数?

3 个答案:

答案 0 :(得分:49)

您想使用random()功能。没有版本不幸返回一个整数,只有0到1之间的浮点数,所以你需要做一些操作。请尝试以下方法:

var randomNum = Math.floor(Math.random() * 10) + 2;

这应该生成2(包括)和12(不包括)之间的随机整数。如果你希望12包含在内,请将10改为11.

答案 1 :(得分:5)

查看此question的答案,它还允许您设置种子值。

答案 2 :(得分:1)

使用Web Crypto api

console.log(

  crypto.getRandomValues(new Uint32Array(1))[0] ,

  crypto.getRandomValues(new Uint16Array(1))[0] ,
  
  crypto.getRandomValues(new Uint8Array(1))[0]
  
)

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues https://caniuse.com/#feat=cryptography