从列表中选择随机段落

时间:2012-06-18 18:05:36

标签: javascript

我目前正在学习Javascript,我想创建自己的Lorem Ipsum生成器。

基本上,我会有一个段落列表(在javascript或HTML文档中?)。

当用户按下 Generate 按钮时,它会从列表中输出3个随机段落。

我在这里环顾四周,但找不到任何有用的东西。

由于

3 个答案:

答案 0 :(得分:3)

你可以简单地拥有一个Javascript数组并选择一个随机索引并将该段落注入DOM元素。我还更新了代码,不再根据您的评论重复之前的随机整数。

示例(代码未经测试)

//global to store previous random int
_oldInt = null;

var paragraphArray = ["Lorem ipsum delor...", "The great white...", "Chitty-chitty-bang-bang..."];  

//update element content (e.g. `<div>` with paragraph)
document.getElementById("MyID").innerHTML = pickRandom(paragraphArray);

var pickRandom = function(paragraphArray){
    //random index of paragraphArray
    var randomInt = Math.floor(Math.random()*paragraphArray.length);
    //ensure random integer isn't the same as last
    if(randomInt == _oldInt)
        pickRandom(paragraphArray);
    else{
        _oldInt = randomInt;
        return paragraphArray[randomInt];
    }
}

答案 1 :(得分:1)

您可以使用Math.random从列表中生成随机索引:

var paragraphs = [...]; # This is your list of paragraphs

function get_random_paragraph() {
    var index = Math.floor(paragraphs.length * Math.random());
    return paragraphs[index];
};

表达式Math.floor(MAX_VALUE * Math.random())生成一个随机整数x,其中0 <= x < MAX_VALUE

答案 2 :(得分:1)

您需要一些paragraphs(此处为JavaScript数组),result框(此处为<div>)和button(此处为... <button>)。

当您点击button时,您想在paragraphs中添加result

var paragraphs = ['Lorem', 'ipsum', 'dolor', 'sit', 'amet'],
    nbParagraphs = paragraphs.length
    paragraph = null,
    result = document.getElementById('result'),
    button = document.getElementsByTagName('button')[0];

button.addEventListener('click', function() {
    /*
     * Math.random() return a number between 0 and 1
     * parseInt() return an integer (the 10 is here to say that we are in decimal)
     * parseInt(Math.random() * nbParagraphs, 10) return a number between 0 and the number of paragraphs, so we can use it to select a paragraph in the paragraphs array
     */
    paragraph = paragraphs[parseInt(Math.floor(Math.random() * nbParagraphs, 10))]
    result.innerHTML += '<p>' + paragraph + '</p>'
})

Here is a demo