Javascript:在数组中搜索字符串,然后计算出现次数 [英] Javascript: search string in array then count occurrences
本文介绍了Javascript:在数组中搜索字符串,然后计算出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 indexOf
在数组中搜索字符串,如何继续计算出现次数?我尝试了后者,但是它不起作用。
var feed = new Array();
var feed = [ testABC, test, testABC];
if(feed.indexOf( testABC)!= -1){
for(var i = 0; i logInfo( found + feed ++);
}
}
解决方案
您可以设置一个计数变量并遍历 feed
的元素。然后检查元素是否具有 indexOf
不等于 -1
(表示已发现)并计数出现次数。
< pre class = snippet-code-js lang-js prettyprint-override>
var feed = [ testABC, test, testABC],count = 0,i; for(i = 0; i< feed.length; i ++){if(feed [i] .indexOf( testABC)!== -1){count ++; }} console.log(count);
I am using indexOf
to search for a string in an array, how can I continue to count the number of occurences? I tried the latter but it isn't working.
var feed= new Array();
var feed= ["testABC", "test", "testABC"];
if (feed.indexOf("testABC") != -1) {
for (var i=0; i < feed.indexOf("testABC").length; i++ ) {
logInfo("found"+feed++);
}
}
解决方案
You can set a count variable and iterate over the elements of feed
. Then check if the element has indexOf
unequal -1
(means found) and count the occurence.
var feed = ["testABC", "test", "testABC"],
count = 0,
i;
for (i = 0; i < feed.length; i++) {
if (feed[i].indexOf("testABC") !== -1) {
count++;
}
}
console.log(count);
这篇关于Javascript:在数组中搜索字符串,然后计算出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文