Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

达夫设备循环问题

今天在看《高性能javascript》这本书,看到达夫设备优化的代码:
do{}while(--n);这里前减,假设是12长度的循环,iterations取整是1,那怎么也不会有第二次8次的循环吧?

//长度
        var a=[1,2,3,4,5,6,7,8,9,10,11,12];
        var iterations=Math.floor(a.length/8);
        console.log("iterations:"+iterations);
        var startAt=a.length%8;
        console.log("取余:"+startAt);
        var count=0;
        do{
            switch(startAt){
                case 0: console.log(count++);
                case 7: console.log(count++);
                case 6: console.log(count++);
                case 5: console.log(count++);
                case 4: console.log(count++);
                case 3: console.log(count++);
                case 2: console.log(count++);
                case 1: console.log(count++);
            }
            startAt=0;
        }while(--iterations);//这里前减,不是就=0了,没有进入下一次循环,最终就4次循环。

结果:
clipboard.png

而我改成while(iterations--),就可以循环全部了,到底咋回事,难道书上印错了,还是我眼睛花了,就大神指点。

clipboard.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

--iterations时

startAt = 4,执行
    case 4: console.log(count++);//0
    case 3: console.log(count++);//1
    case 2: console.log(count++);//2
    case 1: console.log(count++);//3
--iterations = 0---->false停止。

iterations--时

startAt = 4,跳至case 4 执行
    case 4: console.log(count++)//0;
    case 3: console.log(count++)//1;
    case 2: console.log(count++)//2;
    case 1: console.log(count++)//3;
--iterations = 1---->true再来一遍。
startAt=0,跳至case 0,执行
    case 0: console.log(count++);//4
    case 7: console.log(count++);//5
    case 6: console.log(count++);//6
    case 5: console.log(count++);//7
    case 4: console.log(count++);//8
    case 3: console.log(count++);//9
    case 2: console.log(count++);//10
    case 1: console.log(count++);//11
--iterations = 0--->false停止
不加break还会执行后面的case语句。

可能你是switch case不加break怎么运行没搞清楚吧。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...