为什么这个JavaScript代码有效

Why does this javascript code work?

本文关键字:代码 有效 JavaScript 为什么      更新时间:2023-09-26
    <!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(。

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]