这周学习JS。
是否可以使用 Math.random 在数组中返回随机值?该值是否是一个字符串并且仍然有效?
您可以获取浮点数(介于 0 和 1 之间,不包括在内)并将其转换为数组的索引(0 和数组长度之间的整数 - 1)。例如:
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
var randomValue = a[Math.floor(a.length * Math.random())];
读这个:
var arr = [1, 2, 3, 4, 5, 6];
var r = arr[Math.floor(Math.random()*a.length)]; // r will store a value from a pseudo-random position at arr.
是的,这确实是可能的。这是一些示例代码:
<script>
var arr = new Array('a', 'b', 'c', 'd', 'e');
document.write("Test " + arr[Math.floor(Math.random() * ((arr.length - 1) - 0 + 1))]);
</script>
请注意,应使用 Math.floor 而不是 Math.round,以获得均匀的数字分布。
感谢你的帮助。
//My array was setup as such.
var arr = New Array();
arr[0]="Long string for value.";
arr[1]="Another long string.";
//etc...
在您的帮助下,由于我知道数组 (2) 中值的确切数量,所以我做了:
var randomVariable = arr[Math.floor(2*Math.random())]
然后按我的意愿输出 randomVariable 。
谢谢!
你可以使用这个:
var array = [];
for(i = 0; i < 6; i++) {
array[i] = Math.floor( Math.random() * 60 );
}
如果您需要 1 到 100 之间的数字,只需将 Math.random() * 60 更改为 Math.random() * 100。
是的,很有可能做你所要求的
const diceRoll = Array.from({ length: 100 }, (_, i) => {
return i + 1;
});
console.log(Math.random() * diceRoll.length);
那里的代码,为什么它的工作原理是 Math.random 返回一个介于 0 和我们设置的任何值之间的随机数,我们在这里设置的值是 diceRoll.length ,它是 100,因此它将返回一个介于 0 和 99 之间的随机值
console.log(Math.random() * diceRoll.length + 1);
将使其返回 0 到 100 之间的随机值