[英]Error when picking random array element in Javascript: Cannot read properties of undefined
我想從數組中選擇一個隨機元素而不重復,但發生錯誤: Cannot read properties of undefined (reading '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();
})
音頻播放流暢,直到我試圖讓它不再重復。 我做錯了嗎?
單詞[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?
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.