简体   繁体   中英

Show array increment one by one elements upon onclick function

I am trying to print array elements one by one upon onclick. Here's the code through which i am achieving it. The problem with the code, upon first click it does not increment value while it suppose to replace old array element with new +1 element of array.

  function myFunction() { var i = 0; i++; var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits[i]; } 
 <button onclick="myFunction()">Try it</button> <p id="demo"></p> 

You are always setting the i variable with 0. Put that variable out of the myFunction scope and it will work.

 var i = 0; var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { if (i >= fruits.length) i = 0; document.getElementById("demo").innerHTML = fruits[i]; i++; } 
 <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> </script> 

But don't forget you can also have the array and the element selector removed out of the scope of the function, making it simpler (and possible faster). Also, check if you'll not exceed the boundaries of the array before incrementing i again.

Updated code with looping functionality.

 var i = 0; var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { document.getElementById("demo").innerHTML = fruits[i]; i++; if(i == fruits.length){i = 0;} } 
 <button onclick="myFunction()">Try it</button> <p id="demo"></p> 

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