简体   繁体   中英

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. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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