diff options
Diffstat (limited to 'files/zh-cn/web/javascript/reference/global_objects/math/random')
-rw-r--r-- | files/zh-cn/web/javascript/reference/global_objects/math/random/index.html | 10 |
1 files changed, 5 insertions, 5 deletions
diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html index 91796ae506..04602b2699 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html @@ -50,11 +50,11 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <p>这个例子返回了一个在指定值之间的随机整数。这个值不小于 <code>min</code> (如果 <code>min</code> 不是整数,则不小于 <code>min</code> 的向上取整数),且小于(不等于)<code>max</code>。</p> -<pre class="brush: js line-numbers language-js"><code class="language-js">function getRandomInt(min, max) { +<pre class="brush: js line-numbers language-js">function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); - return Math.floor(Math.random() * (max - min)) + min; </code>//不含最大值,含最小值<code class="language-js"> -}</code></pre> + return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值 +}</pre> <div class="note"> <p>也许很容易想到用 <code>Math.round()</code> 来实现,但是这会导致你的随机数处于一个不均匀的分布,这可能不符合你的需求。</p> @@ -64,11 +64,11 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <p>上一个例子提到的函数 <code>getRandomInt()</code> 结果范围包含了最小值,但不含最大值。如果你的随机结果需要同时包含最小值和最大值,怎么办呢? <code>getRandomIntInclusive()</code> 函数可以实现。</p> -<pre class="brush: js line-numbers language-js"><code class="language-js">function getRandomIntInclusive(min, max) { +<pre class="brush: js line-numbers language-js">function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 -}</code></pre> +}</pre> <h2 id="规范">规范</h2> |