我正在构建一个小项目:随机报价生成器。为什么我的按钮每次都不工作,为什么不打印前6个FIRST?
我有6个引号作为对象存储在文件中,quotes.js
。每个报价对象有一个quote
和source
。他们中的一些人也有citation
和year
。
我有一个HTML页面(加上CSS),在屏幕上显示报价。还有一个按钮可以点击:click to get a new quote
。
我的代码很大程度上运行,当我点击我的页面上的按钮时,它随机加载一个新的报价。大多数时候...
但是,我也瞄准不显示一个随机报价不止一次,直到数组中的所有引号显示第一次。
这还没有发生。
我的按钮,随机,不起作用。我可能会获得5次成功的按钮点击,一次失败,然后随机取得另一次成功。我不确定为什么会发生这种情况。
你可以请建议在这里做什么?在控制台中没有发现错误。
实际上,我想按钮每次都工作,它只是再次加载相同的报价。
这里是我的主要代码:
// event listener to respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document.getElementById('loadQuote').addEventListener("click", printQuote, false);
// prints quote
function printQuote(){
var finalQuote = buildQuote();
document.getElementById('quote-box').innerHTML = finalQuote;
}
// builds message for html, adding on citation and/or year if necessary
function buildQuote(){
var quote2Print = getQuote();
var message;
message = "<p class='quote'>" + quote2Print.quote + "</p><p class='source'>" + quote2Print.source;
if(quote2Print.hasOwnProperty('citation') === true){
citation = quote2Print.citation;
message += "<span class='citation'>" + quote2Print.citation + "</span>";
if(quote2Print.hasOwnProperty('year') === true){
year = quote2Print.year;
message += "<span class='year'>" + quote2Print.year + "</span></p>";
return message;
} else {
return message += "</p>";
}
}else {
return message;
}
}
// makes sure that if all 6 quotes haven't been printed, getRandomQuote is called again until a new one is found
function getQuote(){
var countArray = [];
var quote;
if(countArray.length < 6){
quote = getRandomQuote();
while(countArray.indexOf(quote) === -1)
{
if(countArray.indexOf(quote) === -1) {
countArray.push(quote);
return quote;
} else{
quote = getRandomQuote();
}
}
} else {
quote = getRandomQuote();
return quote;
}
}
// With random number, goes through array of quotes and chooses one. random number = index position
function getRandomQuote(){
var randomQuoteNum = randomQuoteNo();
var quote = quotes[randomQuoteNum];
return quote;
}
// Gets a random number
function randomQuoteNo() {
var randomNumber = Math.floor(Math.random() * 6);
return randomNumber;
}
这不是一个好的做法。更好的方法是随机洗牌数组(lookup fisher yates shuffle),然后从数组中依次获取项目。 –
你的'getQuote'函数的逻辑很难遵循。例如'if(countArray.length <6)'将始终为'true',while(countArray.indexOf(quote)=== -1)''将总是只运行一次,因为当这个条件是真正。 – Titus