在Javascript中拾取随机数组元素时出错:无法读取未定义的属性



我想从数组中挑选一个随机元素而不重复,但出现了一个错误:无法读取undefined的属性(读取"sound"(

这是我的代码:

var words = [
{ word: 'major', sound: 'major.mp3'},
{ word: 'apply', sound: 'apply.mp3'},
{ word: 'blue',  sound: 'blue.mp3' },
{ word: 'cat',   sound: 'cat.mp3'  },
{ word: 'class', sound: 'class.mp3'},
{ word: 'code',  sound: 'code.mp3' },
{ word: 'cook',  sound: 'cook.mp3' },
{ word: 'daisy', sound: 'daisy.mp3'},
{ word: 'ease',  sound: 'ease.mp3' },
{ word: 'idea',  sound: 'idea.mp3' }
];
var randomWord = words[Math.floor(Math.random() * words.length - 5)]; // just added - 5 here
var audio = new Audio();
var playBtn = document.getElementById("play-button");
var guessBtn = document.getElementById("guess-button");
var nextBtn = document.getElementById("next-button");
var correct = document.getElementById("correct");
var incorrect = document.getElementById("incorrect");
playBtn.addEventListener("click", function() {
audio.src = randomWord.sound;
audio.play();
var name = words.splice(randomWord,1); // just added
words.push(name); // just added
})
guessBtn.addEventListener("click", function() {
var inputBox = document.getElementById("input-box").value;
if (inputBox == randomWord.word) {
correct.innerHTML = "Correct!"
}
else {
incorrect.innerHTML = "Incorrect"
}
})
nextBtn.addEventListener("click", function() {
location.reload();
})

音频播放得很流畅,直到我试着让它不再重复。我做错了吗?

words[Math.floor(Math.random((*(words.length-1(];

我认为你需要这样使用。

因为Math.floor(Math.random((*words.length-5(可以小于0

您可以考虑:1(构建一个从0到words.length的索引数组,2(选择一个随机索引3(使用随机索引获取一个单词(该单词将是随机的(4(删除随机索引以避免重复。这样,你就不需要删除你的单词,你的随机索引将始终有效。

//----------New code-----------------
var indexes = []
for (let i=0; i<words.length; i++) {
indexes.push(i)
}
//-----------------------------------


playBtn.addEventListener("click", function() {
//get a random index value
let randomIndex = Math.floor((Math.random()*words.length))
//Get your randomword here, using the random index
var randomWord = words[randomIndex]; 
//Delete the index so it will not repeat
indexes.splice(randomIndex,1)
//This is your code below
audio.src = randomWord.sound;
audio.play();
//var name = words.splice(randomWord,1); // delete this!
words.push(name); // just added >> is this required?
})

最新更新