简体   繁体   English

查找数组中所有出现的单词

[英]Find all occurrences of word in array

I'm trying to find the number of total occurrences of a word in an array. 我试图找到一个单词在一个数组中出现的总数。
Here I found a solution and altered it a bit: 在这里,我找到了一个解决方案并将其更改为:

var dataset = ["word", "a word", "another word"];
var search = "word";
var count = dataset.reduce(function(n, val) {
  return n + (val === search);
}, 0);

Here is the fiddle . 这是小提琴

But, instead of 3 I only get 1. So it only finds the first element, which is just word . 但是,我得到的不是3,而是3。因此,它仅找到第一个元素,即word But how to find all elements, containing word ? 但是如何查找包含word所有元素?

Try this: 尝试这个:

var dataset = ["word", "a word", "another word"];
var search = "word";
count = 0;

jQuery(dataset).each(function(i, v){ if(v.indexOf(search) != -1) {count ++} });

Here, count will be 3. 在这里, count为3。

You have to use String.prototype.indexOf() that return the index of the first occurence of the substring in the string, or -1 if not found: 您必须使用String.prototype.indexOf()返回字符串中子字符串首次出现的索引,如果未找到则返回-1

var dataset = ["word", "a word", "another word"];
var search = "word";
var count = dataset.reduce(function(n, val) {
  return n + (val.indexOf(search) > -1 ? 1 : 0);
}, 0);

The operator === means: equal object and equal type. 运算符===表示:相等的对象和相同的类型。

If you are looking for each array element containing the 'search' word you need to use a different operator. 如果要查找包含“搜索”字词的每个数组元素,则需要使用其他运算符。

So, another possible approach, using filter and indexOf , is: 因此,使用filterindexOf的另一种可能的方法是:

 var dataset = ["word", "a word", "another word"]; var search = "word"; var count = dataset.filter(function(val) { return val.indexOf(search) != -1; }).length; document.write('N. words: ' + count) 

You could use String#indexOf . 您可以使用String#indexOf

 var dataset = ["word", "a word", "another word"], search = "word", count = dataset.reduce(function(r, a) { return r + !!~a.indexOf(search); }, 0); document.write(count); 

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

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