我创建了一个数组,当你点击随机单词按钮时会选择一个随机单词,但我仍然坚持创建下一个和上一个单词以便逐步完成列表。
<Script>
window.onload = myFunction;
var WordList = ["a", "b", "c", "d"];
var Word
function myFunction() {
var Word = WordList[Math.floor(Math.random()*WordList.length)];
document.getElementById("Word").innerHTML = Word;
}
function NextWord() {
var a = WordList.indexOf("Word");
document.getElementById("Word").innerHTML = a;
</script>
答案 0 :(得分:0)
你的nextWord()函数没有右括号,你正在寻找字符串“Word”的索引,你宁愿看看indexOf变量Word,这样......
function NextWord() {
var a = WordList.indexOf(Word) ;
/// check if last entry
if((a + 1) == WordList.length) {
/// reset
a = 0;
}else {
/// increment
a += 1;
}
/// set innerhtml
document.getElementById("Word").innerHTML = WordList[a];
}
你可以为PreviousWord()
做同样的事情答案 1 :(得分:0)
缓存数组的当前索引
var currentIndex = 0, wordList = ["a", "b", "c", "d"];
function randomWord() {
currentIndex = Math.floor(Math.random() * wordList.length);
return wordList[currentIndex];
}
function nextWord() {
currentIndex += 1;
currentIndex = Math.min(currentIndex, wordList.length - 1);
return wordList[currentIndex];
}
function prevWord() {
currentIndex -= 1;
currentIndex = Math.max(currentIndex, 0);
return wordList[currentIndex];
}