JavaScript随机报价生成器

时间:2016-05-06 02:07:04

标签: javascript arrays object

我一直在为一个带有一系列对象(引号)的类构建一个随机引用生成器,并根据随机数生成函数显示一个随机引用。为了获得额外的功劳,课程要求我找到一种方法,使报价只显示一次,然后再循环回报价。为此,我决定尝试创建一个空数组,然后将生成的任何引号推送到该数组,并将其从原始数组中切出,然后运行for循环,检查我的原始数组长度是否为0,如果是,循环遍历新数组,将每个索引推回原来的索引。

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

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

有没有办法防止splice创建一个现在留在原始数组中的空数组?当我每次运行代码时都将查看引用和引号都打印到控制台时,它会像

一样开始

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

然后去

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

并且一旦原始数组的长度为0,它将在列表中以[undefined]重置,最终给我错误。

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

谢谢

1 个答案:

答案 0 :(得分:2)

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

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

Here is a Fiddle我测试了它。