var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letter[Math.round(Math.random()*(quotes.length))]
Every time it just returns the last letter, g, not a random one from the array.
What am I doing wrong?
(quotes.length)
What is quotes
? You want letters
.
You're doing var letter = letter
, but letter
hasn't been defined yet. Also, when choosing a random element from an array, use Math.floor
instead of Math.round
:
const letters = ["a", "b", "c", "d", "e", "f", "g", "h"]; const letter = letters[Math.floor(Math.random()*letters.length)]; console.log(letter);
Probably need to fix a few typos in your code:
var letters = ["a", "b", "c", "d", "e", "f", "g", "h"]
var letter = letters[Math.round(Math.random()*(letters.length))]
Also, you may not want to use Math.round
since it can cause an out-of-bound array access error. You should try Math.floor
instead.
修正错别字,您应该会没事的
var letter = letters[Math.round(Math.random()*(letters.length))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.