I was in the middle of coding a slideshow in javascript using jquery, when I ran into something that was doing what my several lines of code was doing in a couple lines.
Problem is, I don't comprehend how it works so I can modify it.
var imgs = [
'image1.jpg',
'image2.jpg',
'image3.jpg'];
var cnt = imgs.length;
$(function() {
setInterval(Slider, 4000);
});
function Slider() {
$('#imageSlide').fadeOut("slow", function() {
$(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
});
}
This is the line that gets me:
[(imgs.length++) % cnt]
I'm reading that as
3+1 % 3 = 1
Now every time it executes, none of that code appears to be modifying any of the variables.
cnt
will always equal imgs.length
(3), imgs.length++
doesn't actually modify it, it just adds one for that single execution, correct?
So matter how many times it executes, it will always be imgs[1]
yet when I execute the code, it runs properly through all the array objects.
EDIT:
I simply added alert(imgs.length);
and confirmed that ++
does actually change the variable, but it still doesn't make sense to me.
The first run, imgs.length = 4
after ++. 4 % 3 = 1
so it should run array object [1]
not [0]
?
Second run, 5 % 3 = 2
Third run, 6 % 3 = 0
etc etc.. but it shouldn't ever reset. However, if I put a alert(imgs.length % cnt);
it only returns 0, 1, 2 than it resets.
Why?