JavaScript随机报价生成器

JavaScript Random Quote Generator

本文关键字:随机 JavaScript      更新时间:2023-09-26

我一直在为一个类构建一个随机引号生成器,该生成器接受一组对象(引号),并基于随机数生成函数显示随机引号。为了获得额外的学分,课程要求我找到一种方法,在再次循环使用引号之前,引号只显示一次。为了做到这一点,我决定尝试创建一个空数组,然后将生成的任何引号推送到该数组,并将其从原始数组中切片,然后运行for循环,检查我的原始数组长度是否为0,如果是,则在新数组中循环,将每个索引推回到原始数组中。

我遇到的问题是,当我从原始数组中拼接出索引时,它会留下一个空数组,该数组现在是循环的一部分,但尚未定义。该索引最终基于随机生成器显示,并带来"未定义"的错误我没有推/拼接方法的代码是-

// event listener to respond to clicks on the page
// when user clicks anywhere on the page, the "makeQuote" function is called
document.getElementById('loadQuote').addEventListener("click", printQuote, false);
//defining variables
var message = '';
var viewedquotes = [];

//print function to print the randomly selected quote to the page
function print(message) {     
        var outputDiv = document.getElementById('quote-box');
        outputDiv.innerHTML = message;
}               
//a function that creates a random number between 0 and the length of quotes to randomly select an object or index of the quotes array and return the value of it.
function getRandomQuote() {
        var quoteObject = quotes[Math.floor(Math.random() * quotes.length)];
        return quoteObject;
}

//RandomColors function to generate random RGB values and return the values

function RandomColors() {
        var red = Math.floor(Math.random() * 256);
        var green = Math.floor(Math.random() * 256);
        var blue = Math.floor(Math.random() * 256);
        var colors = 'rgb(' + red + ',' + green + ',' + blue + ')';
        return colors;
}

//Takes the random quote function stores it into var printObject and adds them to message variable as a string of paragraphs and spans.
//If citation and year are undefined it does not print them.
//Resets the message variable to be '' after for a new click to generate a new quote.  
//Uses the getRandomColors function to change the body's background color each time the button is clicked.
function printQuote() {
        var printObject = getRandomQuote();
        message += '<p class="quote">' + printObject.quote + '</p>';
        message += '<p class="source">' + printObject.source + '';
        if (printObject.citation !== undefined) {
                message += '<span class ="citation">' + printObject.citation + '</span>';
            }
        if (printObject.year !== undefined) {
                message += '<span class ="year">' + printObject.year + '</span>';
            }
        message += '</p>';
        print(message);
        message = '';
        var getRandomColors = RandomColors();
        document.body.style.backgroundColor = getRandomColors;
}

我在最后一个函数中尝试的拼接和推送方法如下(这是在printQuote()函数-中的message=''行之后

var pushQuote = viewedquotes.push(printObject);
                console.log(viewedquotes);
                var indexOfQuote = indexOf(printObject);
                var spliceQuote = quotes.splice(indexOfQuote,1);
                var quotesLength = quotes.length;
                console.log(quotes);
                if (quotesLength === 0) {
                    for (i = 0; i <= viewedquotes ; i++) {
                        quotes.push(viewedquotes[i]);
                    }
            viewedquotes= [];
                }

有没有一种方法可以防止拼接创建一个空数组,而这个数组现在保留在原始数组中?当我每次运行代码时都将viewedquotes和quotes打印到控制台时,它会像一样开始

[对象][对象][对象]

然后去

[对象][对象][对象][对象]

一旦原始数组的长度为0,它就会在列表上重置为[未定义],最终会给我错误。

我知道可能还有其他方法可以完成这项工作,但我只是想知道我的逻辑是否可以进行一些调整?

感谢

您可以调整方法,从引号数组中拼接一个随机索引,然后将其推到第二个数组中的堆栈顶部。类似:

var quotes1 = ["q1", "q2", "q3", "q4", "q5"];
var quotes2 = []; //<==empty array
var indexToSplice = Math.floor(Math.random() * quotes1.length);
var spliceQuote = quotes1.splice(indexToSplice, 1);
print(spliceQuote);
quotes2.push(spliceQuote);

但是,你必须考虑改变。当引号数组为空时,可能会发生这种情况。

if (quotes1.length == 0) {
    quotes1 = quotes2;
    quotes2 = [];
}

这是我测试的Fiddle。