简体   繁体   English

为什么要使用Math.random()及其作用

[英]Why use Math.random(), and what it does

Here I have a piece of code: 这里有一段代码:

if (Math.random() < 0.80) {
    var img = $('#img');
}

$(document).mousemove(function(event) {
    var mouse_x = event.pageX;
    var mouse_y = event.pageY;
    $(img).css({
        'top': mouse_y+'px', 
        'left': mouse_x+'px',
        'display' : 'block',
        'position' : 'absolute'
    }); 
});

In this script, I don't understand what the if (Math.random() < 0.80) line is doing. 在此脚本中,我不了解if (Math.random() < 0.80)行在做什么。 And how does Math.random() gets its value, from where? Math.random()如何从哪里获得其价值?

From developer.mozilla.org 来自developer.mozilla.org

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. Math.random()函数返回一个浮点伪随机数,范围为[0,1),即从0(包括)到不包括1(不包括),然后可以缩放到您的所需范围。 The implementation selects the initial seed to the random number generation algorithm; 该实现为随机数生成算法选择初始种子。 it cannot be chosen or reset by the user. 用户无法选择或重置它。

In your code Math.random() generates a psudeo random number < 1 and then if that number is less than 0.80 the code inside the if block executes. 在您的代码中,Math.random()生成一个小于1的伪随机数,然后如果该数字小于0.80,则会执行if块中的代码。

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

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