简体   繁体   English

如何仅使用Javascript一次显示一个数组元素?

[英]How to show array elements one at a time using only Javascript?

I made a JavaScript array randomizer and it show the elements one at a time with interval. 我做了一个JavaScript数组随机化器,它每次间隔显示一个元素。 I want to make them show one at a time without the interval, but with button. 我想让他们一次显示一个没有间隔但有按钮的显示。 When I click the button it shall switch to the next element, but until then it remains the same. 当我单击按钮时,它将切换到下一个元素,但是直到那时它仍保持不变。 Can you help me do that? 你能帮我吗?

 var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"]; var i = 0; setInterval(function() { document .getElementById('numberList') .innerHTML = numberStrings[i++]; if (i == numberStrings.length) i = 0; }, 2000); function shuffleUsingRandomSwapping(array) { var j, x, i = 0, len = array.length; for (i; i < len; i++) { j = Math.floor(Math.random() * len); x = array[i]; array[i] = array[j]; array[j] = x; } } 
 <button onclick="shuffleUsingRandomSwapping(numberStrings);updateNumberList(numberStrings);">Shuffle Using Random Swapping</button> <div id="numberList"></div> 

 var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"]; var curElement = 0; function updateNumberList() { document .getElementById('numberList') .innerHTML = numberStrings[curElement++]; if (curElement == numberStrings.length) curElement = 0; } function shuffleUsingRandomSwapping(array) { var j, x, i = 0, len = array.length; for (i; i < len; i++) { j = Math.floor(Math.random() * len); x = array[i]; array[i] = array[j]; array[j] = x; } } 
 <button onclick="shuffleUsingRandomSwapping(numberStrings);updateNumberList(numberStrings);">Shuffle Using Random Swapping</button> <div id="numberList"></div> 

I don't know you situation, but if you just want to display a random element from an array each time you press the button, it should be done in a much easier way, without shuffling the array. 我不知道您的情况,但是如果您只想在每次按下按钮时显示一个数组中的随机元素,则应该以一种更加简单的方式来完成,而不必重新排列数组。

 var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"]; function displayRandomElem() { document .getElementById('numberList') .innerHTML = numberStrings[Math.floor(Math.random() * numberStrings.length)]; } 
 <button onclick="displayRandomElem()">Shuffle Using Random Swapping</button> <div id="numberList"></div> 

To show the values in random orders, so that they don't repeat themselves, use the next code: 要以随机顺序显示值,以免重复出现,请使用以下代码:

 var numberStrings = ["One", "Two", "Three", "Four", "Five", "Six"]; function displayRandomElem() { if (numberStrings.length == 0) return; document .getElementById('numberList') .innerHTML = numberStrings.splice(Math.floor(Math.random() * numberStrings.length), 1); } 
 <button onclick="displayRandomElem()">Shuffle Using Random Swapping</button> <div id="numberList"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM