簡體   English   中英

JS:數組的 Math.random

[英]JS: Math.random for array

這周學習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())]

然后按照我的意願輸出隨機變量。

謝謝!

你可以使用這個:

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 之間的隨機值

已經瀏覽了所有這些答案並找到了解決我自己問題的方法,我真的很感激

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM