简体   繁体   中英

How to create and display result one at a time in an infinite loop in javascript?

I'm fairly new to HTML and Javascript. I want to know how to create an infinite loop from, let's say, myArray, list, or whatever and then display result one at a time. Can you please give me an example, hints, or anything with detailed explanation of how it works? I just want to understand on how things work. Thanks!

A very basic loop is a while loop:

while (condition) {
    //code block to be executed
}

Typically you would use it like so:

var i = 0;
while (i < 10) {
    //code block to be executed
    i++; 
    //This block of code will continue until i >= 10 
    //adding 1 to the value of I each iteration
}

Easiest way to do a endless loop:

while (true) {
    code block to be executed
}
//true will always be true so this will continue until it 
//hits a return; statement, the end of time, or the software 
//or hardware gives up

A common mistake that end up in an endless loop:

var i = 0;
while (i < 10) {
    code block to be executed
    //In this example i is never being increased so 
    //i will always be less than 10
}

A very practical way to do a while loop correctly:

var array = ['a','b','c'];
var i = 0;
while (i < array.length) {
    alert(array[i]);
    i++;
}
//This will alert a, alert b, then alert c 

Another way to do the above is using a for loop:

var array = ['a','b','c'];
for (var i = 0; i < array.length; i++) {
     alert(array[i];
}
//for loops are a good practice because you are less 
//likely to leave out steps like defining the iterator,
//or increasing the iterator

OP

I'm trying to create something using HTML/Javascript that everytime I press a button called next item (I created one using <form></form> ) it would display an item, or an image. The trick is I don't know how to keep displaying the item after the last position. After the last position it should go back to the first position. For example, for the array that you provide in your example you have [a, b, c], after I displayed c and press the button again I want to display a again and so forth. Can you give me hints or any other valuable info on how to do this?

Answer

JSFiddle Example:

http://jsfiddle.net/d2809p6z/

HTML

<button id="button">click me</div>

JS

var array = ['a','b','c'];
var index = 0;
document.getElementById('button').onclick=function(){
    if (index >= array.length) {
        index = 0;
    }
    alert(array[index]);
    index++;
};

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