For loops >> Search for your name # 1 - Why is var j = i?


#1


For loops >> Search for your name #1


Why is var j = i?


/*jshint multistr:true */

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 = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
	if (text[i] === "E") {
		// If we find it, add characters up to
		// the length of my name to the 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);
}


#2

i - index where is symbol "E". Look to the first for loop and if statement:

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
	if (text[i] === "E") {
		// If we find it, add characters up to
		// the length of my name to the array
		for(var j = i; j < (myName.length + i); j++) {
			hits.push(text[j]);
		}
	}
}

So, first for loop look for symbol "E" in the variable text using variable i as an iterator. If find it we add characters up to the length which equals to myName variable into the hits array. For this goal we need to use second for loop which started from i where symbol "E" was found.


#3

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