javascript - JS对象赋值无效?
高洛峰
高洛峰 2017-04-11 11:11:39
[JavaScript讨论组]

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

 

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],哪里有问题?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(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);
            }
PHP中文网
    setInterval(
        function(){
            statusObj.func();
            currentIndex=(currentIndex+1)%statusList.length;
            //添加这行
            statusObj=statusList[currentIndex];
            console.log(currentIndex);
        },
        statusObj.timer
    );

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

PHPz

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

怪我咯

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

statusObj.func();换为statusList[currentIndex].func()即可
PHP中文网

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号