So let's say I have an array that looks like this:
weather = ["sun", "clouds", "rain", "hail", "snow"]
And I want to find and display all of the strings which have the letter "s" in them. This is what I think I should do...
for(var i = 0; i < weather.length; i++)
{
if(weather[i].indexOf('s') != -1)
{
alert(weather);
}
}
But that just displays all of the weather strings as many times as there are strings with the letter "s" in them. (It will just alert: "sun, clouds, rain, hail, snow" 3 times)
How do I get it to alert just the specific names of the weather which contain the letter "s"?
You need to do alert(weather[i]) instead of alert(weather)
Check this fiddle
as simple modern solution without vars or loops:
alert(
["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With