A small iteration tip
When coding in JavaScript, it's often needed to constantly iterate through the contents of an array, using a function called from a setInterval
method (example).
Until now, I was doing something like the following:
arrayOfSth = ['one', 'two', 'three'];
count = 0;
function onLoad() {
setInterval(iterate, 1000);
}
function iterate() {
alert(arrayOfSth[count]);
if(count < arrayOfSth.length - 1) {
count++;
} else {
count = 0;
}
}
But, instead of the whole check at the end of the iterate
function to increment (or reset) the count
variable, I'm now doing the following:
count = (count + 1) % arrayOfSth.length;
It has the exact same effect, but it's fancier and cleaner.
Written by Stathis Goudoulakis
Related protips
1 Response
Neat trick, but be aware that clever code can introduce bugs if being maintained by someone unfamiliar with your trickery :) I'd be sure to leave a very descriptive comment by that line.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#