搜索引号数组时得到 'Undefined' - Javascript

Getting 'Undefined' when searching through array of quotes - Javascript

我正在研究一个随机报价生成器,我首先随机生成一个介于 0 和数组长度 'quotes,' 之间的数字,然后 return 该报价。

function getQuote() {
 var quotes = ["I never met a toby that I didn't like ~ Kimya Dawson", "Blood in my beard ~ Aesop Rock", "How many roads must a man walk down? ~ Bob Dylan", "Orange is the new black ~ Jenji Kohan"];

function randomNumber(min, max) {
 var quote = Math.floor(Math.random() * (max - min +1)) + min
 return quotes[quote]; 
}; 
return randomNumber(0, quotes.length);
};
getQuote();

它大部分时间都有效,但有时它会 return 'Undefined.' 我在测试像 'hello,' 这样的单个单词数组时没有遇到这个问题 'green,' 等,它只发生在我添加空格时。

找到随机索引的代码中的 +1 是您的问题。

有 4 个引号,所以 max 是 4。4-0+1 是 5,而不是 4,所以你会每隔一段时间生成值 4,并且数组中的那个位置没有任何内容。 (引号位于索引 0、1、2 和 3。)

Math.floor(Math.random() * (max - min +1)) + min

can return max 指向一个不存在的数组元素。数组索引从 0length - 1.

应该是

Math.floor(Math.random() * (max - min)) + min

数组从 0 开始,因此在您的情况下最大值为 3(引号 [3])。 但是长度函数 returns 元素个数 (4).

return randomNumber(0, quotes.length-1);