Is there a way in javascript to find out how many times a certain string is in an array?
I have an array that I want to find the number of string 'hello'开发者_运维问答
in it. Is there any way to do this?
var count = 0;
for(var i=0; i<myArray.length; i++) {
if(myArray[i] == 'hello') {
count++;
}
}
Assuming it's an array of strings,
var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
if (stringArray[i] == "hello")
++count;
}
And now for something completely different functional:
var count = stringArray.filter(function(x) { return x == "hello" }).length
var arr=['no','hello',2,true,false,'hello','true','hello'];
if(arr.indexOf){
var ax= -1, count= 0;
while((ax= arr.indexOf('hello', ax+1))!= -1)++count;
}
alert(count)
Or
var count = stringArray.reduce(function(a,b){ return (b=='hello')?a+1:a},0)
精彩评论