从数组中随机引用?

时间:2012-07-08 00:22:33

标签: javascript arrays random

  

可能重复:
  Randomizing elements in an array?

我在网上发现了这个“引用旋转器”脚本并且它可以正常工作,但是我想随机化显示引号的顺序,而不仅仅是在列表中循环。任何帮助将不胜感激。

var myquotes = new Array(
    'Quote #1',
    'Quote #2',
    'Quote #3' // Leave the last quote without a comma at the end
    );

function rotatequote()
{
    thequote = myquotes.shift(); //Pull the top one
    myquotes.push(thequote); //And add it back to the end

    document.getElementById('quotetext').innerHTML = thequote;
    t=setTimeout("rotatequote()",10000);
}

// Start the first rotation.
rotatequote();

1 个答案:

答案 0 :(得分:1)

将rotateQuote更改为:

function rotatequote()
{
    var thequote = myquotes[( Math.floor ( Math.random() * myquotes.length ) )];
    document.getElementById('quotetext').innerHTML = thequote;
    var t=setTimeout("rotatequote()",10000);
}