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?
the return value of
imgs.length++is 3 therefore 3 % 3 = 0 butimgs.lengthwill be4and theimgsarray will contain4items.try it in console:
so every time
imgs.length++is called itt will append one item to the array. so not a nice code but short 🙂EDIT: the why is easy to answer, in the start it contains
cntnumber of elements, so the code will step on every image and the starts from the beginning of it. so if theimgsarray contains5items it will step through the5items and starts from the beginning.the only problem with this code, that the array will be increased every time and the memory will be eaten by the browser.