此示例的JavaScript代码说明?

时间:2015-04-30 16:46:10

标签: javascript

大家好!我已经完成了几个简短的JavaScript课程,现在我已经转到了 Heads Up:JavaScript ,这很有趣并且正在帮助巩固我的学习。不过,我确实碰到了一些我不理解的东西。在下面的代码中,我理解程序在执行时通常会做什么,但在尝试跟踪每个执行步骤时,我意识到我对特定段的“什么/为什么/如何”感到困惑。这是我正在查看的示例程序的代码:

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];

            alert(phrase);

        }

        makePhrases();

这段对我来说很困惑:

            var rand1 = Math.floor(Math.random() * words1.length);

            var rand2 = Math.floor(Math.random() * words2.length);

            var rand3 = Math.floor(Math.random() * words3.length);

我知道代码的一部分随机化了每个数组中的哪个项目被选中以形成新的“随机短语”,但我不明白它是如何做到的。我以前也不知道Math.random或Math.floor可以应用于字符串(必须是因为它们在一个数组中,本质上是一个数字?),或者使用Math.random的方式/原因或带字符串的Math.floor。

另外,为什么我们需要使用.length这个化身?它有什么作用?我非常感谢你的智慧,并花时间帮助那些不熟悉编码的人,而且还有很多值得学习的东西!

3 个答案:

答案 0 :(得分:3)

让我们看一下代码:

var rand1 = Math.floor(Math.random() * words1.length);

Math.random()会在00.999999..之间返回一个数字。

words1是可供选择的字词列表。

words1.length是列表的大小,项目数量,在这种情况下为5

Math.random() * words1.length会在04.99999..之间返回一个数字。

最后使用Math.floor()获取04之间的整数。

然后,此数字将用作words1中的索引,因此words1[rand1]

因此,Math操作永远不会在字符串上使用,只在最后一步中获取字符串。

答案 1 :(得分:0)

您想从数组中选择一个随机元素。所以你需要一个索引,换句话说是从04的随机数(因为你的长度是5)。 Math.random会在01之间提供一个随机数(不包括1)。因此,要将其转换为0到4之间的随机数,您需要乘以5的长度。

然后,由于我们需要一个整数,而不是浮点数,我们使用Math.floor将其截断为整数。

答案 2 :(得分:0)

Math.random()  //Return a random number between 0-1
words1.length()  //Return the length of the array
Math.floor()     //Return the closest integer less than or equal to a given number.

现在表达式:

(Math.random() * words1.length) 

将返回介于0和数组长度之间的随机数。可能是一个浮点数,例如3,4:

Math.floor(Math.random() * words1.length)

将在0和字符串长度之间返回整数数字,因此您现在可以将其用作字符串(表现得像数组)索引器。

注意:请注意,随机数介于0(含)和1(独占)之间,这就是使用Math.floor()安全的原因,以避免异常,这就是为什么没有使用Math.ceiling