I'm using swipejs from swipejs.com, the home page slider uses this logic to highlight the active un-ordered list element and I'd like to know how this while condition works.
<ul id="bullets">
<li></li>
....
</ul>
var bullets = document.getElementById('bullets').getElementsByTagName('li');
var elem = document.getElementById('mySwipe');
window.mySwipe = Swipe(elem, {
callback: function(index, element) {
var i = bullets.length;
while (i--) {
bullets[i].className = ' ';
}
bullets[index].className = 'on';
}
});
The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
This question already has answers here: In various codes where time limit exceeded, by using while(t-- >0) instead of while(t--) code runs successfully.
The JavaScript while statement creates a loop that executes a block as long as a condition evaluates to true . The while statement evaluates the expression before each iteration of the loop. If the expression evaluates to true , the while statement executes the statement . Otherwise, the while loop exits.
Loops can execute a block of code as long as a specified condition is true.
The number 0
is considered falsey in JavaScript, so the while loop will run until it hits 0. You would have to be sure that i is positive to start off with, otherwise you've got an infinite loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With