带有continue语句的Javascript嵌套while循环的行为与预期不符
Javascript nested while loop with continue statement not behaving as expected
我正在尝试使用嵌套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++;
}
相关文章:
- for循环中的javascript if语句找不到==
- 循环通过数组的If语句不起作用
- 使用if语句重新循环
- for 循环和 if 语句,获取变量并存储它
- 使用javascript中的for循环和if语句
- 当使用return语句时,循环不会中断
- Javascript:用if语句运行while循环,用子句随机生成内容
- 在 for 循环中使用 if 语句
- 识别两个文本中的单词(if 语句在 for 循环中)
- for 循环中的 if 语句
- 如何使用for循环语句通过Ajax发送大数据数组
- ++ 在 While 循环语句中是什么意思
- 标签如何与非循环语句一起使用
- 如何在JavaScript中写出这个基本的循环语句?
- 试着写一个do-while循环语句来打印我的语句,但是它目前没有打印它
- Selenium RC / Python / JavaScript .aspx /循环语句
- 如何获取数组中多个文件的值而不需要任何循环语句
- 不能在同一个if语句中运行两个for循环语句
- 怎么样..循环语句在Javascript中工作?(ECMAScript 6)
- javascript中的循环语句没有按照预期的方式运行