Reputation: 495
Just practicing some for loops and I'm not sure why it is outputting nothing:
['']
This is the code:
var text = "This is a long piece of Liam text with a bit of Liam text in the Liam";
var myName = "Liam";
var hits = [""]
for (var i=0; i >= text.length; i++)
{
if (myName[i] === "L")
{
for (var j=i; j < (myName.length + i); j++)
{
hits.push(i);
}
}
}
if (hits.length === 0)
{
console.log("Your name wasn't found!");
}
else
{
console.log(hits);
}
I don't think my push function is actually pushing the letters into the array properly?
Upvotes: 2
Views: 83
Reputation: 495
for (var i=0; i <= text.length; i++)
{
if (text[i] === "L")
{
for (var j=i; j < (myName.length + i); j++)
{
hits.push(text[j]);
}
}
}
The code within the second nested for loop is also wrong - changed it from:
for (var j=i; j < (myName.length + i); j++)
{
hits.push(i);
}
Upvotes: 0
Reputation: 57719
Just as an FYI, you can do:
text.indexOf(myName) !== -1; // true if myName occurs in text
or, if you want to be really clever:
text.match(new RegExp("\b" + myName + "\b")); // \b = word boundary = amazing
// wont match "NotLiam", will match "Hi, I'm Liam."
Upvotes: 3
Reputation: 5812
for (var i=0; i >= text.length; i++)
actually means the variable i will start from 0 and every time before execution of the code block to check if the condition i >= text.length is met, if the condition doesn't hold, the code block will not be executed. The last part of i++ means after each iteration of the code block defined after, run this statement.
Since the text length appearing longer than 0, so the first check i (equals to 0) greater or equals to the text length (which is 69) fails and the push is never invoked.
Upvotes: 1
Reputation: 844
for (var i=0; i >= text.length; i++)
{
if (myName[i] === "L")
{
for (var j=i; j < (myName.length + i); j++)
{
hits.push(i);
}
}
}
the foor loop is wrong
it should be:
for (var i=0; i <= text.length; i++)
Upvotes: 0
Reputation: 6010
for (var i=0; i >= text.length; i++)
should be
for (var i=0; i < text.length; i++)
Upvotes: 4