幻灯片/轮播在特定条件下无法正常工作?

Slideshow / Carousel not working properly in a specific condition?

此 JS 代码无法正常工作。是什么原因?

let indexOfSlide = 1; // update me !
show(indexOfSlide);

function liveSlide(n){
   show(indexOfSlide = n); // update me !
}

function plusSlidesItem(n){
   show(indexOfSlide += n);
}

function show(indexOfSlide) {
    let slides_item = document.getElementsByClassName("slides-item");
    let tiny_img = document.getElementsByClassName("tiny-img");
    let i;
    
    if( indexOfSlide < 1){
        indexOfSlide = slides_item.length;
    }
    if( indexOfSlide > slides_item.length){
        indexOfSlide = 1;
    }

    for(i=0;i<slides_item.length;i++){
        slides_item[i].style.display = "none";
    }

    for(i=0;i< slides_item.length; i++){
        tiny_img[i].style.opacity = "0.5";
    }

    slides_item[indexOfSlide-1].style.display = "initial";
    tiny_img[indexOfSlide-1].style.opacity = "1" ;
}

当 indexOfSlide 在 show() 函数的参数中被替换为 n 并且在 show() 中的两个 if 语句条件中,它就可以正常工作。为什么?

这里可以进行一些代码重构。

let indexOfSlide = 1; // update me !

// we might as well use the global variable indexOfSlide instead of
// passing it as a parameter since it is updating at each call
function show() {
    let slides_item = document.getElementsByClassName("slides-item");
    let tiny_img = document.getElementsByClassName("tiny-img");

    if( indexOfSlide < 1 ){
        indexOfSlide = slides_item.length;
    } else if( indexOfSlide > slides_item.length ){
        indexOfSlide = 1;
    }

    // you can merge both the loops since they are
    // iterating over the same index sequence
    for(let i = 0; i < slides_item.length; i++){
        slides_item[i].style.display = "none";
        tiny_img[i].style.opacity = "0.5";
    }

    slides_item[indexOfSlide - 1].style.display = "initial";
    tiny_img[indexOfSlide - 1].style.opacity = "1" ;
}

// calling the show() function after it has been defined
// is how it should be done else it'll throw an error

show();

function liveSlide(n){
   indexOfSlide = n;
   show(); // update me !
}

function plusSlidesItem(n){
   indexOfSlide += n;
   show();
}

看看它是否解决了问题