javascript-我不断收到“ Uncaught ReferenceError:未定义imgArray”错误

我已经写了一些代码作为对象来淡入和淡出一些图像,只有当我要求构建幻灯片时,我才得到一个

“Uncaught ReferenceError: imgArray is not defined”.

任何人都可以帮助我为什么会出现此错误.谢谢.

const slideShow = {
  curIndex: 0,imgDuration: 10000,slider: document.querySelector('.banner__slider').childNodes,imgArray: [
    'images/background/img3.jpg','images/background/img1.jpg','images/background/img2.jpg'
  ],buildSlideShow(arr) {
    for (i = 0; i < arr.length; i++) {
      const img = document.createElement('img');
      img.src = arr[i];
      slider.appendChild(img);
    }
  },slideShow() {

    function fadeIn(e) {
      e.className = "fadeIn";
    };

    function fadeOut(e) {
      e.className = "";
    };

    fadeOut(slider[curIndex]);
    curIndex++;
    if (curIndex === slider.length) {
      curIndex = 0;
    }

    fadeIn(slider[curIndex]);

    setTimeout(function () {
      slideShow();
    },imgDuration);
  },}; 

slideShow.buildSlideShow(imgArray).slideShow();
最佳答案
因为代码中没有imgArray变量,所以出现了错误.您可以将其更改为:

slideShow.buildSlideShow(slideShow.imgArray).slideShow();

这样可以解决一个问题,但会造成另一个问题. buildSlideShow方法不返回任何内容.因此,.slideShow()方法将再次引发错误.由于imgArray是slideShow对象的属性,因此可以使用this关键字.将方法更改为:

buildSlideShow() {

  for (i = 0; i < this.imgArray.length; i++) {
    const img = document.createElement('img');
    img.src = this.imgArray[i];
    slider.appendChild(img);
  }

  return this;
}

从buildSlideShow中,使用return this返回对象的实例.这样,您可以链接方法.

const slideShow = {
  curIndex: 0,// slider: document.querySelector('.banner__slider').childNodes,buildSlideShow() {
    console.log("inside buildSlideShow method");
    
    for (i = 0; i < this.imgArray.length; i++) {
      console.log(this.imgArray[i]);
      const img = document.createElement('img');
      img.src = this.imgArray[i];
      //slider.appendChild(img);
    }
    
    return this;
  },slideShow() {
    console.log("inside slideShow method")
  }
}

slideShow.buildSlideShow()
         .slideShow();

(我已注释掉滑块代码)

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小