繁体   English   中英

Math.random() 以百分比形式应用?

[英]Math.random() applied as a percentage?

所以我有这个代码,它为我提供了一些图像的顶部和左侧属性的随机数。

    var random1 = Math.ceil(Math.random() * 500);
var random2 = Math.ceil(Math.random() * 500);

$(document).ready(function () {

    $('#randomp').css('top', random1);
    $('#randomp').css('left', random2);

});

问题是我更愿意将 1 到 100% 之间的数字随机化。 那可能吗?

Math.floor(Math.random() * 100) + 1 + '%'

由于Math.random返回随机数,不小于0且小于1 ,因此您只需将结果乘以99而不是500即可获得介于1100 % 之间的数字。

最后,代码应该如下:

var random1 = Math.round(Math.random() * 99) + 1;
var random2 = Math.round(Math.random() * 99) + 1;

这给你一个 0 到 100 之间的数字(都包括在内): Math.floor(Math.random() * 101);

  1. Math random 会给你一个介于 0(包括)和 1(不包括)之间的数字
  2. 如果将该数字与 101 相乘,它将为您提供一个介于 0(包括)和 101(不包括)之间的数字
  3. Math.floor 将返回小于或等于上述数字的最大整数。

不确定你是否想要它四舍五入,所以这里有两个:

 console.log( rando(1, 100) + "%" ); console.log( rando(1, 100, "float") + "%" );
 <script src="https://randojs.com/1.0.0.js"></script>

这使用randojs.com使随机性变得简单易读。 如果您需要了解更多信息,请查看网站。

暂无
暂无

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

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