[英]Why does my loop condition not work by comparing a variable to itself?
var text = "dave kdfkdf dave kdfkdfffff dave";
var myName = "dave";
var hits = new Array();
var counter;
var nameCounter;
for (counter = 0; counter <= text.length; counter++){
if (text[counter] === myName[0]) {
for (nameCounter=counter; nameCounter < (nameCounter+myName.length); nameCounter++) {
hits.push(text[nameCounter]);
}
}
}
the code above does not work, but when I change the condition of the second loop to: 上面的代码不起作用,但是当我将第二个循环的条件更改为:
nameCounter < (counter+myName.length);
then it does work. 然后它确实起作用。
can you explain, why? 你能解释为什么吗? thanks :)
谢谢 :)
Simple math. 简单的数学。 I understand myName can be any name, with any length, but let's stick with "dave" and length of 4 and change myName.length to the hard-coded value of 4:
我知道myName可以是任何名称,具有任何长度,但是让我们继续使用“ dave”和4的长度,并将myName.length更改为4的硬编码值:
we're left with the following as the condition for your loop. 我们将以下内容作为循环的条件。 it's never false, thus never stops*...
它永远不会虚假,因此永远不会停止* ...
nameCounter < nameCounter + 4
*well, until it overflows, or run out of memory, etc. *好,直到溢出或内存不足等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.