Javascript下一个、上一个、来自数组的随机
我已经创建了一个数组,当你点击random word按钮时会选择一个随机单词,但是我一直在创建next和previous,以便逐步浏览列表Javascript下一个、上一个、来自数组的随机,javascript,html,Javascript,Html,我已经创建了一个数组,当你点击random word按钮时会选择一个随机单词,但是我一直在创建next和previous,以便逐步浏览列表 <Script> window.onload = myFunction; var WordList = ["a", "b", "c", "d"]; var Word function myFunction() { var Word = WordList[Math.
<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>
nextWord函数没有右括号,您正在查找字符串单词的索引,您更希望查找变量单词的索引,如下所示
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];
}
您可以对上一个Word执行相同的操作,缓存数组的当前索引
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];
}
这是打字错误吗?你从未关闭过你的NextWord函数。WordList.indexOfWord;返回-1,因为Word不在该数组中。我认为它应该是Math.mincurrentIndex,wordList.length-1Wow。。非常感谢。我用了这个,它工作了,除了下一个,当它结束时,得到了一个未定义的。我认为它已经超过了arraymy的错误,请检查a+1==Wordlist.length