Javascript/p5.js中的独立随机数生成 [英] Independent random generations in Javascript / p5.js

查看:195
本文介绍了Javascript/p5.js中的独立随机数生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在P5.js中,为了获得独立的随机数,我经常不得不编写多行随机数,例如:

In P5.js, I often have to write more than one line of random in order to get independent random generation such as :

random();
random();
random();

// or 
a = random();
b = random();
c = random();

//etc

p5.js或javascript中是否有任何其他代码可以执行相同/相似的生成,因此可以提高代码效率? 谢谢

is there any alternative code(s) in p5.js or javascript that can perform the same/similar generations and so the code efficiency can be improve? Thanks

推荐答案

如果要将随机数放入数组中,可以使用Array.from简洁地实现它:

If you're putting random numbers into an array, you can do it concisely with Array.from:

const random = () => Math.random();

const arr = Array.from({ length: 3 }, random);
console.log(arr);

您可以通过分解对多个单独的变量执行相同的操作:

You can do the same sort of thing for multiple separate variables by destructuring:

const random = () => Math.random();

const [a, b, c] = Array.from({ length: 3 }, random);
console.log(a);
console.log(b);
console.log(c);

如果您需要使用某些参数调用random,则:

If you need to call random with certain parameters, then:

const random = (low, high) => Math.floor((high - low) * Math.random()) + low;

const [a, b, c] = Array.from({ length: 3 }, () => random(1, 4));
console.log(a);
console.log(b);
console.log(c);

这篇关于Javascript/p5.js中的独立随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆