![](/img/trans.png)
[英]Trying to select a random index from an array - always giving me last index of the array
[英]Picking a random index from an array is always returning me the same index?
var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letter[Math.round(Math.random()*(quotes.length))]
每次它只返回最后一個字母g,而不是數組中的隨機字母。
我究竟做錯了什么?
(quotes.length)
什么是quotes
? 你要letters
。
您正在執行var letter = letter
,但是letter
尚未定義。 另外,從數組中選擇隨機元素時,請使用Math.floor
而不是Math.round
:
const letters = ["a", "b", "c", "d", "e", "f", "g", "h"]; const letter = letters[Math.floor(Math.random()*letters.length)]; console.log(letter);
可能需要修復代碼中的一些拼寫錯誤:
var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letters[Math.round(Math.random()*(letters.length))]
另外,您可能不想使用Math.round
因為它可能會導致超出范圍的數組訪問錯誤。 您應該改用Math.floor
。
修正錯別字,您應該會沒事的
var letter = letters[Math.round(Math.random()*(letters.length))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.