JS对象赋值无效?

本意:
循环执行3个函数,来改变ul节点的className,2秒后执行wait,3秒后执行stop,1秒后执行pass,依次循环。
HTML部分

 <ul id="traffic" class="wait">
     <li><span></span></li>
     <li><span></span></li>
     <li><span></span></li>
  </ul>

JS部分

var statusList=[
      {
        func:function(){
          traffic.className='wait';
        },
        timer:2000
      },
      {
        func:function(){
          traffic.className='stop';
        },
        timer:3000
      },
      {
        func:function(){
          traffic.className='pass';
        },
        timer:1000
      }
      ];
      
    var currentIndex = 0;
    var statusObj=statusList[currentIndex];
    setInterval(
        function(){
            statusObj.func();
            debugger;
            currentIndex=(currentIndex+1)%statusList.length;
            console.log(currentIndex);
        },
        statusObj.timer
    );

即使右边的statusList[currentIndex]在改变,statusObj变量一直是statusList[0],哪里有问题?

阅读 7.6k
5 个回答

哥们,你只更新了下标序号,没有更新statusObj对象啊,它只被赋值了一次,就是数组内的第一个元素啊,你可以将

 function(){
                statusObj.func();
                debugger;
                currentIndex=(currentIndex+1)%statusList.length;
                console.log(currentIndex);
            }

改成

function(){
                statusObj.func();
                debugger;
                currentIndex=(currentIndex+1)%statusList.length;
                statusObj = statusList[currentIndex];
                console.log(currentIndex);
            }
    setInterval(
        function(){
            statusObj.func();
            currentIndex=(currentIndex+1)%statusList.length;
            //添加这行
            statusObj=statusList[currentIndex];
            console.log(currentIndex);
        },
        statusObj.timer
    );

另外建议,用id直接当全局变量使用的方法在大型开发中尽量少用

currentIndex=(++currentIndex)%statusList.length;可以吗

var statusObj=statusList[currentIndex];//这里的statusObj已经是定值了,即statuslist[0];
如果你想要动态变化

statusObj.func();换为statusList[currentIndex].func()即可

谢谢各位的回答,确实是少写了一条语句。然后这个函数这样写的话是实现不了我想要的循环的。

   setInterval(
        function(){
            statusObj.func();
            currentIndex=(currentIndex+1)%statusList.length;
            statusObj=statusList[currentIndex];
        },
        statusObj.timer
    );

setInterval只执行一次,循环执行的是里面的回调函数。因此statusObj.timer的值只取了一次,不会更新变化...我这个新手老犯这种想当然的错误。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题