简体   繁体   中英

JavaScript Random Quote Generator

I have been building a random quote generator for a class that takes an array of objects (quotes) and displays a random quote based on a random number generating function. For extra credit the course has asked me to find a way to make it where the quotes only display once before looping back through the quotes again. To do this I decided I would try creating an empty array and then push whatever quote is generated to that array, and slice it out of the original array, then run a for loop that checks if my original array length is 0, if it is, loop through the new array pushing each index back into my original one.

The issue I am running into, is that when I splice out the index from the original array, it leaves behind an empty array that is now part of the loop but is undefined. That index eventually shows up based on the random generator and brings an error of 'undefined.' My code without the push/splice method is -

// 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;
}

The splicing and pushing methods I was trying with the last function are as follows (this was after the message = '' line inside the printQuote() function -

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= [];
                }

Is there a way to prevent splice from creating an empty array that is now left in the original one? When I printed both the viewedquotes and quotes to the console each time running the code, it would start out like

[object][object][object][object] [object]

then go

[object][object][object] [object][object]

and once the original array would have length of 0 it would reset with an [undefined] on the list, eventually giving me the error.

I know there may be other methods to completing this but I am just wondering if my logic is do-able with some tweaks?

Thank you

You could adjust your method to splice a random index from the quote array, then push it onto the top of the stack in the second array. Like:

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);

But then you have to consider the change up. That can happen when the quote array is empty.

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

Here is a Fiddle where I tested it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM