The other day I was doing a javascript exercise and wound up with a weird behavior. I would appreciate if you could explain it. so the goal was to make a little script that creates all the possible combinations of consequent letters in a word.
eg. "dog" >>> ["d", "do", "dog", "o", "og", "g"];
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;
}
so everything runs cool and smooth but there is something I can't figure out.
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
as you can see in log line:10 interpreter enters the if statement and increases "i" by 1 and set the "y" to the value of "i" so they both have value of 1 but by the time interpreter gets back to the loop "y" gets increased by 1 again. since "y" should not undergo the increment by the loop yet, I couldn't explain it in anyway.I mean shouldn't we set the y to "i+1" in the script?doesn't that make more sense?
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire