Javascript Next, Prev, Random from an array
Javascript Next, Prev, Random from an array
我创建了一个数组,当你点击随机单词按钮时选择一个随机单词,但我坚持创建下一个和上一个,以便逐步通过列表。
<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()函数没有右括号,你正在寻找字符串"Word"的索引,你更想看看变量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()
缓存数组的当前索引
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];
}
相关文章:
- 如何为json对象中的段发送array[]
- Array.length似乎不起作用;console.log则显示其他情况
- 如何迭代Array.prototype函数
- Javascript 新的 Array 和 join() 方法
- Array.lenght = undefined
- Javascript setTimeout for an array
- Javascript - element.childNodes does not see an append.newch
- NodeJS API调用中Array中的Push和Pull元素
- 如何在MongoDB中将String转换为Array
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- 您的平台不支持RxJS-Array.observe
- Get JSON from an url
- Using this.selectedIndex inside an array in an 'onchange
- Passing an array to jade rendering
- jQuery grepping an array[]
- drawImage from an array
- Javascript Next, Prev, Random from an array
- Angular.isArray(data) returns false for an Array
- Javascript Reduce an empty array
- getElementById with an array Javascript