Second For loop (different solution) It works, is it correct?


#1

https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5

var text = "Onore Alex Ipsum Guttenberg A666 datus Alex"
var myName = "Alex"
var hits = []
for (var i=0; i < text.length; i++){
    if (text[i] === 'A') {
        for (var c=0; c < myName.length; c++ ){		        	
            hits.push(text[i + c]);
	}
    }
}


#2

It works because the offset is present. However, it will be slower since the offset must be added to the index in each iteration. Adding the offset in the conditional only has to perform that action once, and the index sequence is offset. Of course with this material, speed is not a factor so obviously either way is fine.


#3

Thanks man, this is the answer I was looking for!


#4

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