为什么 foreach classlist.remove 迭代不起作用?

Why the foreach classlist.remove iteration is not working?

我的滑块中的这段代码有问题。 我需要从所有数组元素中删除 class。数组的长度可能会有所不同。 此代码有效:

updateGallery() {
    this.carouselArray.forEach((el, i ) => {
        el.classList.remove('gallery-item-1');
        el.classList.remove('gallery-item-2');
        el.classList.remove('gallery-item-3');
        el.classList.remove('gallery-item-4');
        el.classList.remove('gallery-item-5');
    });
    let carouselSliceLength = this.carouselArray.slice().length;
    this.carouselArray.slice(0, carouselSliceLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

但是这段代码不起作用:

updateGallery() {
    this.carouselArray.forEach((el, i ) => {
       el.classList.remove(`gallery-item-${i+1}`);
    });
    let carouselSliceLength = this.carouselArray.slice().length;
    this.carouselArray.slice(0, carouselSliceLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

为什么?

因为你们在做不同的事情。在第一个实现中,您要为数组中的一个元素删除五个不同的元素(remove 函数的五次调用)。

而第二个实现只为每个元素调用一个 remove。所以对于第一个元素,它将删除 gallery-item-1 第二个 gallery-item-2 等等

好的,开发者。 我在循环中循环并更正了代码。 此代码有效。删除 类 并添加新的。 3d 滑块有效。

updateGallery() {
    const carouselLength = this.carouselArray.length
    this.carouselArray.forEach(el => {
        for (let i=1; i<=carouselLength; i++) {
            el.classList.remove(`gallery-item-${i}`);
        }
    });
    this.carouselArray.slice(0, carouselLength).forEach((el, i) => {
        el.classList.add(`gallery-item-${i+1}`);
    });
}

谢谢!