对象的随机数组

时间:2018-10-04 20:15:40

标签: javascript arrays javascript-objects

所以我有这个数组:

var musicQuiz = [
  {
    lyrics: "Now the drugs don´t work",
    answers: [
      "The Verve",
      "Oasis",
      "Adele",
      "Rolling Stones",
      "Chris de Burgh",
      "Ceasars"
    ]
  },
  {
    lyrics: "Go your own way",
    answers: [
      "The Chemical Brothers",
      "U2",
      "The Doors",
      "Fleetwood Mac",
      "Moloko",
      "The Beatles"
    ]
  }
];

我想随机显示“歌词”。所以我有这个:

for (var i = 0; i < musicQuiz.length; i++) {
  var question = document.getElementById("question");
  var random = Math.floor(Math.random() * musicQuiz[i].lyrics.length);
  question.textContent = musicQuiz[i].lyrics[random];
}

但是它不起作用,只显示一个字母。我看到了如何使用数组执行此操作,但无法弄清楚如何执行此操作。任何帮助和解释都将很好。

3 个答案:

答案 0 :(得分:6)

您仔细查看歌词,并从每个歌词中提取一个随机字符并将其设置为DOM,因此,页面的最后将包含最后一个歌词中的随机字符。您想改用随机歌词:

 var question = document.getElementById("question");
 var random = Math.floor(Math.random() * musicQuiz.length);
 question.textContent = musicQuiz[random].lyrics;

答案 1 :(得分:0)

将歌词分成数组

    for (var i = 0; i < musicQuiz.length; i++) 
        {
           var question = document.getElementById("question");
           var lyricsArray = musicQuiz[i].lyrics.split(" ");
           var random = Math.floor(Math.random() * lyricsArray.length);
           question.textContent = lyricsArray[random];
        }

答案 2 :(得分:0)

首先随机排列数组(您也可以随机排列答案)。然后根据需要进行枚举,将随机组合的元素插入dom ...

let quiz = [
  { lyrics: 'hey jude, whats up with you?',
    answers: [ 'ac/dc', 'the beatles', 'queen' ]
  },
  { lyrics: 'walk like an egyption',
    answers: [ 'guns and roses', 'the bengals', 'bee gees' ]
  },
  { lyrics: 'heard it from a friend who, heard it from a friend who',
    answers: [ 'led zepplin', 'reo speedwagon', 'the eagles' ]
  },
];

let shuffledQuiz = _.shuffle(quiz);
shuffledQuiz.forEach(quizElement => {
      console.log(quizElement.lyrics);
      // insert into your dom here
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>