JavaScript 中 -10 到 10 之间的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3594177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:22:21  来源:igfitidea点击:

Random number between -10 and 10 in JavaScript

javascriptrandom

提问by coure2011

Possible Duplicate:
Generating random numbers in Javascript

可能的重复:
在 Javascript 中生成随机数

How do I get a random number between ?10 and 10 in JavaScript?

如何在 JavaScript 中获得 10 到 10 之间的随机数?

回答by Darin Dimitrov

var min = -10;
var max = 10;
// and the formula is:
var random = Math.floor(Math.random() * (max - min + 1)) + min;

回答by Akyegane

jQuery: $.randomBetween(minValue, maxValue);

jQuery: $.randomBetween(minValue, maxValue);

回答by Akyegane

For example:

例如:

var min = -10;
var max = 10;

console.log(Math.floor(Math.random() * (max - min + 1) + min));
.as-console-wrapper { max-height: 100% !important; top: 0; }

See this jsrandom.phpfor some comparison of Math.floor, Math.ceiland Math.round.

有关,和 的一些比较,请参阅此jsrandom.phpMath.floorMath.ceilMath.round

回答by Adam Matan

Using not more than a simple Google search,

只使用一个简单的谷歌搜索

var randomnumber=Math.floor(Math.random()*21)-10

Math.random()*21)returns a number between 0 and 20. Substracting 10 would yield a random number between -10 and 10.

Math.random()*21)返回一个介于 0 和 20 之间的数字。减去 10 将产生一个介于 -10 和 10 之间的随机数。

My advice: try to Google first, and than ask about the results, e.g.:

我的建议:先尝试谷歌,然后询问结果,例如:

What is the best way to get a random number? I've googled and found methods X and Y, and wondered which is best for purpose Z.

获得随机数的最佳方法是什么?我在谷歌上搜索并找到了方法 X 和 Y,并想知道哪个最适合用途 Z。