有没有办法在javascript中找出某个字符串在数组中的次数?

时间:2022-06-29 23:58:35

I have an array that I want to find the number of string 'hello' in it. Is there any way to do this?

我有一个数组,我想在其中找到字符串'hello'的数量。有没有办法做到这一点?

5 个解决方案

#1


2  

var count = 0;
for(var i=0; i<myArray.length; i++) {
    if(myArray[i] == 'hello') {
        count++;
    }
}

#2


2  

Assuming it's an array of strings,

假设它是一个字符串数组,

var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
  if (stringArray[i] == "hello")
    ++count;
}

#3


0  

And now for something completely different functional:

现在,对于功能完全不同的东西:

var count = stringArray.filter(function(x) { return x == "hello" }).length

var count = stringArray.filter(function(x){return x ==“hello”})。length

#4


0  

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)

#5


0  

Or

var count = stringArray.reduce(function(a,b){ return (b=='hello')?a+1:a},0)

#1


2  

var count = 0;
for(var i=0; i<myArray.length; i++) {
    if(myArray[i] == 'hello') {
        count++;
    }
}

#2


2  

Assuming it's an array of strings,

假设它是一个字符串数组,

var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
  if (stringArray[i] == "hello")
    ++count;
}

#3


0  

And now for something completely different functional:

现在,对于功能完全不同的东西:

var count = stringArray.filter(function(x) { return x == "hello" }).length

var count = stringArray.filter(function(x){return x ==“hello”})。length

#4


0  

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)

#5


0  

Or

var count = stringArray.reduce(function(a,b){ return (b=='hello')?a+1:a},0)