查找数组中的特定字符

时间:2021-10-20 20:23:06

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...

我想找到并显示其中包含字母“s”的所有字符串。这就是我认为我应该做的......

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)

但是,这只会显示所有的天气字符串,因为字母中包含字母“s”。 (它只会提醒:“太阳,云,雨,冰雹,雪”3次)

How do I get it to alert just the specific names of the weather which contain the letter "s"?

如何让它仅提醒包含字母“s”的天气的具体名称?

4 个解决方案

#1


4  

You need to do alert(weather[i]) instead of alert(weather)

你需要做警报(天气[i])而不是警报(天气)

Check this fiddle

检查这个小提琴

#2


2  

as simple modern solution without vars or loops:

作为没有变量或循环的简单现代解决方案:

alert(
  ["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)

#3


1  

Oh. I think I was just missing a small detail.

哦。我想我只是错过了一个小细节。

for(var i = 0; i < weather.length; i++)
{
    if(weather[i].indexOf('s') != -1)
    {
        alert(weather[i]);
    }
}

#4


0  

very simple

很简单

 weather = ["sun", "clouds", "rain", "hail", "snow"];

      weather.forEach(function(arrayItem,arrayIndex,array){
              if(array[arrayIndex].match('s')){
               alert(array[arrayIndex]);
              }
      })

Explanation:

说明:

forEach() method calls a function for each element in the array.
arraytItem like='sun' , 'clouds' etc.
arrayIndex=position of arrayItem;
array=weather;

forEach()方法为数组中的每个元素调用一个函数。 arraytItem like ='sun','clouds'等arrayIndex = arrayItem的位置;阵列=天气;

#1


4  

You need to do alert(weather[i]) instead of alert(weather)

你需要做警报(天气[i])而不是警报(天气)

Check this fiddle

检查这个小提琴

#2


2  

as simple modern solution without vars or loops:

作为没有变量或循环的简单现代解决方案:

alert(
  ["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)

#3


1  

Oh. I think I was just missing a small detail.

哦。我想我只是错过了一个小细节。

for(var i = 0; i < weather.length; i++)
{
    if(weather[i].indexOf('s') != -1)
    {
        alert(weather[i]);
    }
}

#4


0  

very simple

很简单

 weather = ["sun", "clouds", "rain", "hail", "snow"];

      weather.forEach(function(arrayItem,arrayIndex,array){
              if(array[arrayIndex].match('s')){
               alert(array[arrayIndex]);
              }
      })

Explanation:

说明:

forEach() method calls a function for each element in the array.
arraytItem like='sun' , 'clouds' etc.
arrayIndex=position of arrayItem;
array=weather;

forEach()方法为数组中的每个元素调用一个函数。 arraytItem like ='sun','clouds'等arrayIndex = arrayItem的位置;阵列=天气;