When a regex has the global flag set, test() will advance the lastIndex of the regex. Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!
So since watermelon follows banana - which returned true - the stored lastIndex influences the point from which the next test is made and the match fails. The solution is simple: remove the g flag. You'd only use that in a regex if you were searching for multiple matches in the same string (which would go some way to explaining the exhibited behaviour).
This had me scratching my head for a few minutes - I don't typically use
RegExp.test
...So it looks like the problem is caused by this documented behaviour:
So since watermelon follows banana - which returned true - the stored lastIndex influences the point from which the next test is made and the match fails. The solution is simple: remove the
g
flag. You'd only use that in a regex if you were searching for multiple matches in the same string (which would go some way to explaining the exhibited behaviour).That's true. I have explained this weird behavior in my this article
I already found that document since the first comment. Anyway, I edited the post mentioning your comment. Thank you.
Oh - and one suggestion in terms of naming - I wouldn't use
food
in your iterator or array name:It might seem pedantic; but at this point you're testing whether they are food; so I'd use generic terms
item
anditemList
.