繁体   English   中英

为什么这个javascript代码有效?

[英]Why does this javascript code work?

    <!doctype html>
<html lang="en">
<head>
<title>Phrase-o-matic</title>
<meta charset="utf-8">
<style>
body {
    font-family: Verdana, Helvetica, sans-serif;
}
</style>
<script>

function makePhrases() {
    var words1 = ["24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win"];
    var words2 = ["empowered", "value-added", "oriented", "focused", "aligned"];
    var words3 = ["process", "solution", "tipping-point", "strategy", "vision"];

    var rand1 = Math.floor(Math.random() * words1.length);
    var rand2 = Math.floor(Math.random() * words2.length);
    var rand3 = Math.floor(Math.random() * words3.length);

    var phrase = words1[rand1] + " " + words2[rand2] + " " + words3[rand3];
    var phraseElement = document.getElementById("phrase");
    phraseElement.innerHTML = phrase;
}
window.onload = makePhrases;
</script>
</head>
<body>
<h1>Phrase-o-Matic says:</h1>

<p id="phrase"></p>

</body>
</html>

这是我在javascript上阅读的一本书的例子为什么:

var rand1 = Math.floor(Math.random() * words1.length);
    var rand2 = Math.floor(Math.random() * words2.length);
    var rand3 = Math.floor(Math.random() * words3.length);

生成值总是向下舍入到数组words1words2words3的索引值? 为什么它永远不会得到高于最后一个索引号4的值

Math.random() * words1.length表示[0, words1.length) 所以值总是小于words1.length

floor()向下舍入(总是向下)到最接近的整数。 Math.random()生成一个大于或等于0且小于1的数字。

如果长度为4,则random()将生成0到3.9999999999之间的数字,并向下舍入。 因此,对于4元素数组,该值始终是有效索引(0到3,包括0和3)。

Math.random()返回0(包括)和1(不包括)之间的值。 所以你可能会得到0.1234。 然后将此乘以数组的长度,在这种情况下为4。 最低可能值为0 * 4 = 0,最高可能值为0.9999 * 4 <4。

floor函数截断数字,只留下整数部分,它将在0,1,2或3范围内。

Math.random()在[0,1 ]中返回一个浮点值,表示:

从0(含)到最高但不包括1(独家)

因此Math.random()* 4将为[0,4],而Math.floor意味着:

小于或等于数字的最大整数

所以Math.floor([0,3.xxxx ...])表示[0,3]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM