Second For loop. What's the difference?


So I was stuck in the second for loop, then I found the answer online, but to be honest, I don't get the difference between the two codes.

This doesn't work:

        for (var j = i; j < text[i] + myName.length; j++)

This works:

for(j = i; j < (myName.length + i); j++);


It tells me my code doesn't push the values to the hits array. My name is in the text, so I know that's not a problem.
What's the differecne? What did I do wrong?


Seems like you should just read them while keeping firmly in mind what the loop should be doing. If there's some part there that you don't know what it does then that's what you need to look into. If you know what each part does then you are able to read that code.

Neither is correct.
If you don't know what they should be doing then you have to start there, otherwise you have no reference to what is correct.

If you're having trouble reasoning about what it does then start with what you know and add on one thing at a time, convincing yourself of why that one additional part is required. Since neither is correct there will be parts that don't make sense to do, which is why you must begin by making sure that you are clear on what it should do so that you can identify this.


Looks closely at what variables you are using. Go through each one and try figure out what the program would actually read from this.


In this case, the statement is checking from the index i of the whole string to the length of the variable myName. So this means that if your name is 6 alphabets long and the first alphabet of your name occurs at index 23, then the statement starts from index 23 and goes till index 29 (23 + 6), which will be the length of your name.

In this case, though, when you say text[i], it corresponds to the value of the string at that index. So if your name is Alyssa and the first letter of your name occurs at index 23, the for conditions says that start from index 23 and go on if it is less than 'A' + 6, instead of saying 23 + 6.


That makes sense.... <--(-^-)-->


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.