<!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);生成始终向下舍入为数组words1、words2和words3中的索引值的值?为什么它永远不会得到大于最后一个索引号4的值
发布于 2013-12-18 11:07:11
Math.random() * words1.length的意思是[0, words1.length)。因此,该值始终小于words1.length。
发布于 2013-12-18 11:08:50
floor()向下舍入(总是向下)到最接近的整数。Math.random()生成一个大于等于0小于1的数字。
如果长度为4,random()将生成一个介于0和3.9999999999之间的数字,并向下舍入。因此,对于4元素数组,该值始终是有效的索引(0到3,包括0到3)。
发布于 2013-12-18 11:08:57
Math.random()返回一个介于0(包括)和1(不包括)之间的值。例如,你可能会得到0.1234。然后将其乘以数组的长度,在本例中数组的长度为4。最低可能值为0.9999 * 4 =0,最高可能值为0*4<4。
floor函数截断数字,只留下0、1、2或3范围内的整数部分。
https://stackoverflow.com/questions/20648960
复制相似问题