javascript 随机_JavaScript中的随机性食谱

javascript 随机

Random behaviour is often required in JavaScript, from drawing stars scattered across the night sky to animating chaotic attractors. But there are many different kinds of randomness, and the type you need will differ depending on the application.

JavaScript中通常需要随机行为,从绘制散布在夜空中的星星到动画混乱的吸引子。 但是,随机性有许多 ,根据应用的不同,所需的类型也会有所不同。

基本随机性 (Basic Randomness)

The simplest form of randomness is the Math.random() function built into JavaScript. In the console:

最简单的随机形式是内置在JavaScript中的Math.random()函数。 在控制台中

> Math.random()
0.19401081069372594

Math.random() always returns a floating-point number between 0 and 1.

Math.random()始终返回0到1之间的浮点数。

Technically, the number returned by Math.random() could be 0, but will never be exactly 1.

从技术上讲, Math.random()返回的数字可能为0,但永远不会完全为1。

Because it’s so frequently used, Math.random() is often placed inside its own function in a script:

由于它经常使用,因此Math.random()通常放在脚本中自己的函数中:

function getRandom() {
  return Math.random();
}

The problem, of course, is that the function will always create a random number within a very limited range; most of the other code recipes on this page are designed to address this.

当然,问题在于该函数将始终在非常有限的范围内创建一个随机数。 此页面上的其他大多数代码食谱都旨在解决此问题。

数字之间的随机性:包含最小值,排除最大值 (Randomness Between Numbers: Min Included, Max Excluded)

Extending this functionality requires a little bit of math:

扩展此功能需要一些数学运算:

浮点 (Floating Point)

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}
getRandomFloat(11, 101)
> 75.31898734299466

整数 (Integer)

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

getRandomInt(10, 20)
> 12

范围内的随机整数,包括最小值和最大值 (Random Integer In Range, Both Min & Max Included)

function getRandomInRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

getRandomInRange(1, 10)
> 7

投币(随机对/错) (Coin Toss (Random True / False))

If you want a simple random 0 or 1 to represent a coin toss:

如果您希望简单的随机0或1代表抛硬币:

function coinToss() {
    return Math.floor(Math.random() * 2);
}
coinToss();
> 0

If you prefer actual true and false values:

如果您喜欢实际的truefalse值:

function coinToss() {
    return (Math.floor(Math.random() * 2) === 0);
}
coinToss();
> true

Or alternatively:

或者:

function coinToss() {
	Math.random()<.5 cointoss>
   
   

Or if you want to associate any other words with the coin sides ( yes / no, heads / tails, etc):

或者,如果您要将其他任何单词与硬币侧面相关联(是/否,正面/反面等):

function coinFlip() {
    return (Math.floor(Math.random() * 2) === 0) ? "up" : "down";
}
coinToss();
> up

随机排除 (Random With Exclusions)

For a limited range of integers: create an array of numbers that you’d like to draw from and select randomly from the array:

对于有限范围的整数:创建一个要从中绘制数字的数组,然后从该数组中随机选择:

var numPool = [ 1, 3, 5, 7, 9, 10 ],
rand = numPool[Math.floor(Math.random() * numPool.length)];

For something a little more dynamic: add an array of the numbers you want to exclude, and an empty array to contain the result of filtering the first array into the second:

为了更生动一点:添加一个要排除的数字数组,以及一个空数组以包含将第一个数组过滤为第二个数组的结果:

var numPool = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var excludePool = [ 3, 4 ];
var filteredPool = [];

Then loop through the numPool array, test if the number drawn from the array exists in excludePool, and place the result in filteredPool:

然后循环遍历numPool数组,测试从数组中得出的数字是否在excludePool ,然后将结果放入filteredPool

for (var i = 0; i < numPool.length; i++) {
    if (excludePool.indexOf(numPool[i]) === -1) {
        filteredPool.push(numPool[i]);
    }
}

Finally, draw a random number from filteredPool:

最后,从filteredPool绘制一个随机数:

var rand = filteredPool[Math.floor(Math.random() * filteredPool.length)];

随机,非重复 (Random, Non-Repeating)

For a small set of numbers: create an array filled with elements, shuffle them randomly, put the results into a new array, then pop out the shuffled elements one at a time:

对于一小部分数字:创建一个由元素组成的数组 ,将它们随机混洗,将结果放入新数组中,然后一次pop一个混洗的元素:

var numPool = [ 13, 21, 36, 14, 27, 10 ];
	
function shuffle(numPool) {
    for(var j, x, i = numPool.length; i; j = parseInt(Math.random() * i), x = numPool[--i], numPool[i] = numPool[j], numPool[j] = x);
    return numPool;
};
var randomResult = shuffle(numPool);
while( randomResult.length > 0 ) {
    console.log( randomResult.pop() );
}

For a larger set of numbers, create and fill the array with random integers, rejecting any that have been previously generated:

对于更大的一组数字,请使用随机整数创建并填充数组,拒绝先前生成的任何整数:

var numReserve = []
while (numReserve.length < 12) {
  var randomNumber = Math.ceil(Math.random() * 1000);
  var found = false;
  for (var i = 0; i < numReserve.length; i++) {
    if (numReserve[i] === randomNumber){ 
        found = true;
        break;
    }
  }
  if (!found) { numReserve[numReserve.length]=randomNumber; }
}

In the code above, numReserve is filled with 12 random numbers between 0 and 1000; the numbers can then be lifted from the array.

在上面的代码中, numReserve填充了12个介于0和1000之间的随机数; 然后可以从数组中取出数字。

密码随机性 (Cryptographic Randomness)

None of these methods create numbers with enough randomness for cryptographically secure functions (and arguably, Math.random() isn’t nearly random enough). For those, we can use the Web Cryptography API by creating a typedArray:

这些方法都不能为加密安全函数创建具有足够随机性的数字(并且可以说Math.random()几乎不够随机 )。 对于这些,我们可以通过创建typedArray来使用Web密码学API:

var cryptoStor = new Uint16Array(8);

(In this case, we’re creating an array with eight different slots that can each contain an unsigned 16-bit integer. Other interger options include Int8Array, Uint8Array, int16Array, Int32Array and Uint32Array.

(在这种情况下,我们正在创建一个具有八个不同插槽的数组,每个插槽可以包含一个无符号的16位整数。其他整数选项包括Int8ArrayUint8Arrayint16ArrayInt32ArrayUint32Array

Then, fill the array with random numbers of the defined type:

然后,使用定义类型的随机数填充数组:

window.crypto.getRandomValues(cryptoStor);

Showing the collected values in the console:

在控制台中显示收集的值:

> [43484, 57947, 46691, 49849, 24272, 11827, 28203, 17423]

The Web Cryptography API has good support in modern browsers, although it is vendor prefixed in some cases.

Web加密API 在现代浏览器中具有良好的支持 ,尽管在某些情况下以供应商为前缀。

翻译自: https://thenewcode.com/82/Recipes-for-Randomness-in-JavaScript

javascript 随机

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值