前几天我正在做一个javascript练习并且结束了一个奇怪的行为。如果你能解释一下,我将不胜感激。 所以我们的目标是创建一个小脚本,创建一个单词中所有可能的后续字母组合。
例如。 "狗" >>> [" d","做","狗"," o"," og","克"];
function combCheck(w){
var arrayBase = [];
for (var i=0, y=1 ; y<=w.length; y++){
arrayBase.push(w.slice(i,y));
console.log("i is equal to: "+i);
console.log("y is equal to: "+y);
if (y==w.length) {
i++;
y = i;
console.log("i in if part is equal to: " + i);
console.log("y in if part is equal to: " + y);
}
}
return arrayBase;
}
所以一切都运行得很酷,但有些东西我无法弄清楚。
combCheck("dog");
VM720:5 i is equal to: 0
VM720:6 y is equal to: 1
VM720:5 i is equal to: 0
VM720:6 y is equal to: 2
VM720:5 i is equal to: 0
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 1
VM720:11 y in if part is equal to: 1
VM720:5 i is equal to: 1
VM720:6 y is equal to: 2
VM720:5 i is equal to: 1
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 2
VM720:11 y in if part is equal to: 2
VM720:5 i is equal to: 2
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 3
VM720:11 y in if part is equal to: 3
你可以在日志行中看到:10解释器输入if语句并增加&#34; i&#34;按1并设置&#34; y&#34;达到&#34; i&#34;的价值因此,当解释器返回循环时,它们都具有1 但的值。&#34; y&#34;再次增加1。 因为&#34; y&#34;不应该通过循环增加,我无论如何都无法解释它。我的意思是我们不应该将y设置为&#34; i + 1&#34;在脚本中?哪个更有意义?
提前致谢。
答案 0 :(得分:0)
您的行为并非异常。在for循环中,变量的迭代位于尾部。您可以考虑执行代码,然后通过向y
添加1来结束。
如果您希望迭代在开头,那么您可以使用while循环,并使循环中的第一个语句为y++
。