Home > Web Front-end > JS Tutorial > body text

javascript 获取m到n之间的随机随机数

WBOY
Release: 2016-06-01 09:54:24
Original
1596 people have browsed it

本文实例讲述了js计算任意值之间随机数的方法。分享给大家供大家参考。具体实现方法如下:

首先:Math.random()这个方法就是计算随机数的返回大于等于0小于1的随机数,

Math.random()*10岂不是返回大于等于0返回小于10吗,但是他只能返回小于10的数,不能返回10,怎么办呢,我们在原来的函数上再加1就变成了Math.random()*10+1;此时就可以返回1到10的随机数了,但是我们返回的很多是小数,不符合要求,下面就用到了Math.floor()这个函数了,这个函数执行向下舍入,也就是说10.99经过Math.floor都是10,Math.ceil(是向上舍入)即使是10.00001,返回也是11,现在我们就求出来结果了:

<code class="language-javascript">Math.floor(Math.random()*10+1);</code>
Copy after login

这样就能求出结果了。

 

那2到10之间的函数怎么办,直接上代码

<code class="language-javascript">Math.floor(Math.random()*9+2);</code>
Copy after login

 

那3到11呢,4到88呢,每次这样自己算也不是办法,下面给大家介绍个通用方法;

<code class="language-javascript">function selectfrom (lowValue,highValue){
    var choice=highValue-lowValue+1;
    return Math.floor(Math.random()*choice+lowValue);
}</code>
Copy after login

然后直接调上面的方法就OK

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!