带有continue语句的Javascript嵌套while循环的行为与预期不符

Javascript nested while loop with continue statement not behaving as expected

本文关键字:循环 语句 continue Javascript 嵌套 while 带有      更新时间:2023-09-26

我正在尝试使用嵌套while循环和continue语句查找3个数组的所有排列。它几乎可以按照我的意愿工作,但当控制权交还给外环时,它添加了一个额外的元素。我将使用递归重写它,但我想知道它为什么要这样做。这里有一个链接:http://jsbin.com/fuyup/15/edit

谢谢你的建议。

function findPermutations() {
    var g1 = ['a1', 'a2'],
        g2 = ['b1', 'b2', 'b3'];
        g3 = ['c1', 'c2', 'c3', 'c4'];
    var g1p = 0,
        g2p = 0, 
        g3p = 0,
        g1len = g1.length,
        g2len = g2.length,
        g3len = g3.length, 
        temp = [],
        result = [];
    outerloop: while (g1p < g1len) {
        temp.push(g1[g1p]);
        while (g2p < g2len) {
            temp.push(g2[g2p]);
            while (g3p < g3len) {
                temp.push(g3[g3p]);
                result.push(temp);
                temp = [];  
                g3p++;
                continue outerloop;
            }
            g3p = 0;
            g2p++;
        }
        g2p = 0;
        g1p++;
    }
    return result;
}

有了continue和备用temp = []重置,您的控制流真的一团糟。

在执行g3p = 0;和最里面的循环(推送结果并重置temp)之前,流跳回到temp.push(g2[g2p]);,在同一个temp数组上调用两次。我在这里不详细介绍……如果需要了解,请使用调试器并逐步执行。

我已经制作了一个使用continue的工作版本,但我并不是很幸运:

outerloop: while (g1p < g1len) {
    temp.push(g1[g1p]);
    while (g2p < g2len) {
        temp.push(g2[g2p]);
        while (g3p < g3len) {
            temp.push(g3[g3p]);
            result.push(temp);
            temp = [];  
            g3p++;
            continue outerloop; 
        }
        g3p = 0;
        temp = [];
        g2p++;
        continue outerloop; 
    }
    g2p = 0;
    temp = [];
    g1p++;
    // continue outerloop; (implicit)
}

你可以在这里看到对称的结构,在每一个层面上都会发生同样的事情。每当我们进入outerloop以获得序列时

temp.push(g1[g1p]); temp.push(g2[g2p]); temp.push(g3[g3p]); result.push(temp);

执行时,我们重置之前的temp


创建排列的通常想法是不使用continue,而是嵌套使数组发生突变的正常for循环,并获取每个状态的快照以附加到结果:

temp = [];
g1p = 0;
while (g1p < g1len) {
    temp[0] = g1[g1p];
    g2p = 0;
    while (g2p < g2len) {
        temp[1]= g2[g2p];
        g3p = 0;
        while (g3p < g3len) {
            temp[2] = g3[g3p];
            result.push(temp.slice());
            g3p++;
        }
        g2p++;
    }
    g1p++;
}