我正在構建一個小項目:隨機報價生成器。爲什麼我的按鈕每次都不工作,爲什麼不打印前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