I signed up for Codecademy and I am currently in the Javascript path. So, there is this lesson called "Search Text for Your Name" and it consists of writing a multi line string and including your name on it and then write a loop that finds your name and logs it to the console. This is the code:
/*jshint multistr:true */
var text = "Blah Blah Pedro Blah Blah Blah Blah Pedro \
Blah Blah Blah Blah Pedro Blah Blah";
var myName = "Pedro";
var hits = [];
for (var i=0; i < text.length; i++){
if (text[i] ==="P"){
for (var j = i; j <(i + myName.length); j++){
hits.push(text[j]);
}
}
}
if (hits.length===0){
console.log("Your name wasn't found!");
}
else {
console.log(hits);
}
The part that confuses me is the second for loop. When I read "A Byte of Python",it said that when a variable = anothervariable, the variables point to the same place in the memory of the computer. But in the JavaScript code, if I change it, like instead of using hits.push(text[j]) I use hits.push(text[i]) or just switch them in any part of the loop the result is always different. Why is that so? How does Javascript treat this kind of variables?
2 Answers 2
That's a nested for-loop. The outer loop loops over all of the text. When it finds a particular letter, the 'inner' loop kicks off and runs until j gets to this number: i + myName.length.
The whole time that inner loop is running, i is not being incremented.
Think of like this. Imagine you have a (Python style) list of words:
for someword in some_list:
for y in someword:
# This inner loop runs for EVERY x in some_list
# whatever runs here, runs for the `length` of someword
# Done with inner loop: back to dealing with outerloop
# Do something with someword, etc.
The reason that switching hits.push(text[j]) for hits.push(text[i]) results in different hits, is that you are pushing different variables with different values: i, and j.
Comments
It takes whatever is stored in 'i' and assigns it to the var 'j'.
More stuff to read about assignment: http://www.w3schools.com/js/js_operators.asp
variable = anothervariable" If that was written there, it is (most likely) wrong. Each variable is usually stored in its own memory location. If you havex = y, then the value ofyis copied to the location ofx.