I am watching a javascript tutorial to create testimonial slider.in this javascript project i didn't understand why they use "slides.length-1".Why cant we give only slide.length only.why -1 should be included in the code can anybody explain?
const next = document.querySelector('.next');
const prev = document.querySelector('.prev');
const slides = document.querySelectorAll('.slide');
let index = 0;
display(index);
function display (index) {
slides.forEach((slide) => {
slide.style.display = 'none';
});
slides[index].style.display = 'flex';
}
function nextSlide () {
index ;
if (index > slides.length - 1) {
index = 0;
}
display(index);
}
function prevSlide () {
index--;
if (index < 0) {
index = slides.length - 1;
}
display(index);
}
next.addEventListener('click', nextSlide);
prev.addEventListener('click', prevSlide);
CodePudding user response:
This is all because we count indexes from 0
Imagine having an array of length 5. This means that array has 5 elements.
But their indexes are: 0, 1, 2, 3, 4 (five elements in total).
That's why when you want to access last element of any array you use:
myArray[myArray.length - 1]
which is literally myArray[5 - 1]
so myArray[4]
. And as I mentioned, indexes in array of length 5 are: 0, 1, 2, 3 and last but not least: 4
CodePudding user response:
Because the numbering in JS going from 0. If you have array with 5 strings - length = 5. when we want to iterate an array we start from 0. Example: var test = ['1', '2', '3', '4', '5'];
// test.length = 5; // but '1' is on 0 position. '2' on 1, '3' on 2d position, '4' on 3, and '5' on 4th postion. If index not - 1, he will search for 5th element, but we don't have it