【问题标题】:Javascript Random Number?Javascript随机数?
【发布时间】:2010-11-10 20:09:33
【问题描述】:

我有以下脚本:

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);
}

在上面写着: if((Timer%10=="0")||(Timer=="1")){

如何使 10 成为 2 到 12 之间的随机数?

【问题讨论】:

标签: javascript random


【解决方案1】:

您想使用random() 函数。不幸的是,没有返回整数的版本,只有 0 和 1 之间的浮点数,因此您需要执行一些操作。请尝试以下操作:

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

这应该会生成一个介于 2(包括)和 12(不包括)之间的随机整数。当然,如果您希望 12 具有包容性,请将 10 更改为 11。

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

    使用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

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多