如何解决未捕获的类型错误:无法读取随机报价生成器未定义的属性"0"?



我有一个jQuery代码的随机报价生成器片段,它给了我以下控制台错误:

当我点击按钮时,它成功地显示了第一个报价,但随后停止。

这是我的代码:

jQuery(document).ready(function(){
jQuery("#change").click(function(){
var quotes = [
["It Crowd" ],
["Black Books"],
["Still Game"],
["quote 4"],
];
// generate random integer< array.length
var number = Math.floor(Math.random()* (quotes.length+1));
//get the elements or just put them in the document write below
var showQuotes = quotes[number][0];

//                      
jQuery("#quotecontent").fadeOut("medium",function(){
var newer = jQuery(
'<div id="content"><p id="quote">'  + showQuotes + '</p></div>' ); 
jQuery(this).replaceWith(newer);
jQuery('#quotecontent').fadeIn("medium");
});                          
});    
});

这是HTML

<div id="quotecontent">
<p id="quote">This is the original quote</p>
</div>
<div id="btn-container">
<button id="change">Press</button>
</div>

这是错误信息:

未捕获类型错误:无法读取未定义的属性"0">

我知道它与代码的这一部分有关:

var showQuotes = quotes[number][0];

但我只是不确定为什么它不起作用,因为我对阵列有点陌生。如果有人能帮助我理解为什么这不起作用,我将不胜感激!!!

Codepen(如果有帮助(:https://codepen.io/kiaramelissa/pen/XWXqgVa

尝试删除此行的[0]:

var showQuotes = quotes[number][0];

引号[number]将返回存储在该位置的字符串。有了[0],你将永远找不到任何东西,因为引号[number]是最终值,而不是数组。

编辑:

更改:

var quotes = [
["It Crowd" ],
["Black Books"],
["Still Game"],
["quote 4"],
];

收件人:

var quotes = [
"It Crowd",
"Black Books",
"Still Game",
"quote 4"
];

最新更新