javascript 在数组中查找特定字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16367012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding a specific character in an array
提问by isolatedhowl
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”的天气的特定名称?
回答by karthikr
You need to do alert(weather[i])
instead of alert(weather)
你需要做alert(weather[i])
而不是alert(weather)
Check this fiddle
检查这个小提琴
回答by dandavis
as simple modern solution without vars or loops:
作为没有变量或循环的简单现代解决方案:
alert(
["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)
回答by isolatedhowl
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]);
}
}
回答by Upvesh Kumar
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 的位置;
数组=天气;