javascript - Why does the second for loop need +i? -
i understand of , how works, except: why second loop need "+i"? , why can't replaced "+1"?
text = "blah blah blah blah blah blah eric blah blah blah eric blah blah eric blah blah blah blah blah blah blah eric"; var myname = "eric"; var hits = []; // "e" in text for(var = 0; < text.length; i++) { if (text[i] === "e") { // if find it, add characters // length of name array for(var j = i; j < (myname.length + i); j++) { hits.push(text[j]); } } } if (hits.length === 0) { console.log("your name wasn't found!"); } else { console.log(hits); }
the j loop offset i.
i runs 0 text.length, say, 0 100.
whenever "e" found j loops i i + myname.length, instance 50 54.
you have j loop 0 myname.length , text[j + i].
note code not "eric", looks "e" , records next 4 characters. if input string "eaebec foo" result [ "eaeb", "ebec", "ec f" ]
Comments
Post a Comment