简体   繁体   English

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

[英]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. 我有一个数组,我想在其中找到字符串'hello'的数量。 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;
}

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

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)

要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM