I have a question regarding the code that determines if the user is on the very last image and press next in my slider. In this case we reset the slider and make current equal to 1 (the first image).

I just can't get my head around this code.

//if last image
else if (current -1 === imgsLen){
    current = 1;
}

I think it makes more sense to write it like this:

//if last image
else if (current === imgsLen +1){
    current = 1;
}

Both versions work fine. I would appreciate if someone could explain the logic in the first statement. Thanks!

有帮助吗?

解决方案

The logic that it is exactly the same, and there's no "better" way between the two. At this point it's mostly semantics: do you want to indicate that one before the current one is the same as the length of the imgs, or do you want to indicate that the length of the imgs is one smaller than the current one. For example:

I want to see if I will have enough money to buy this toy after receiving another penny:

if (currentCash + 0.01 === toyPrice) {}

I want to see if the price of this toy costs exactly 1 penny more than what I currently have:

if (currentCash === toyPrice - 0.01) {}

Again, it's just semantics at this point: what are you trying to say in this if-statement?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top