从 API 调用中,如何获取字段并查看该值重复了多少次

From an API call, how can I grab a field and see how many times that value is being repeated?

本文关键字:多少次 字段 调用 API 何获取 获取      更新时间:2023-09-26

代码:

    var textArray = new Array();
    var allText = results.data._contained.text;
    for (var i = 0; i < allText.length; i++) {
        var text1 = allText[i];
        var textHtml = "<div id='text_item'>";
        textHtml += "<span class='some_div'>{0}</span>".replace("{0}", text1.text_is);
        textHtml += "</div>";
        textArray.push(text1.texts.priority);
        $("#text_box").append(textHtml);
    }
    if (foo === 'Some text') {
        document.write("match");
    } else {
        document.write("not match");
    }
}

我有上述逻辑,它工作正常,但我被困在以前没有做过的事情上。

这就是我想做的:

范围.some_div将包含字符串值。 我想做的是计算相同的值重复多少次。 我该怎么做?

示例:假设值为"医学",它在.some_div中独立重复 10 次。 如何返回重复次数的计数?

您可以使用

String.split 函数来实现这一点,如果text1.text_is(这是 .some_div span 的内容)是 String 类型。

var wordsCount = {};
var allWords = text1.text_is.split(" ") //split by space or the delimiter of the words.
for (var i = 0, l = allWords.length; i < l; i++)
{
    var word = allWords[i];
    wordsCount[word] = (wordsCount[word] || 0) + 1;
}

祝你好运

最有效和方便的方法是将 string.match() 与正则表达式一起使用。这具有允许不区分大小写的额外好处。

function countWords(text) {
  var resultArray = [];
  var text = $(".some_div").text(); //store the original text
  text = text.replace(/'W/g, " "); //replace non-alphanumerics with a whitespace
  text = text.replace(/'s{2,}/g, " "); //replace more than one space with a single space
  while (text.length > 0) {
    var index = text.indexOf(" "); //find the first space
  
    if (index === 0) {
      text = text.slice(1, text.length); //this is a leading space, skip it
    } else {
      var wordToMatch = text.slice(0, index); //find the first word
      var regex = new RegExp(wordToMatch, "gi"); //create case-insensitive regular expression with the word
      var wordCount = text.match(regex).length; //get number of word occurences
      resultArray.push({ word: wordToMatch, count: wordCount }); //store the result for this word
      text = text.replace(regex, ""); //remove this word from the input text
      text = text.replace(/'s{2,}/g, " "); //replace more than one space with a single space again
    } 
  }
  return resultArray;
}
countWords($(".some_div").text()).forEach(function(item) {
  $("#result").append(item.word + ": " + item.count + "<br/>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class='some_div'>The field of Medicine is a medicine Field</span>
<br/>
<div id="result"></div>