[英]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))]
Every time it just returns the last letter, g, not a random one from the array. 每次它只返回最后一个字母g,而不是数组中的随机字母。
What am I doing wrong? 我究竟做错了什么?
(quotes.length)
What is quotes
? 什么是
quotes
? You want letters
. 你要
letters
。
You're doing var letter = letter
, but letter
hasn't been defined yet. 您正在执行
var letter = letter
,但是letter
尚未定义。 Also, when choosing a random element from an array, use Math.floor
instead of Math.round
: 另外,从数组中选择随机元素时,请使用
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);
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. 另外,您可能不想使用
Math.round
因为它可能会导致超出范围的数组访问错误。 You should try Math.floor
instead. 您应该改用
Math.floor
。
修正错别字,您应该会没事的
var letter = letters[Math.round(Math.random()*(letters.length))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.