Home > Web Front-end > JS Tutorial > JS implements statistics on data patterns within strings

JS implements statistics on data patterns within strings

php中世界最好的语言
Release: 2018-06-05 09:19:51
Original
2501 people have browsed it

This time I will bring you JS implementation statisticsStringData patterns within strings, JS statistics string data patternsWhat are the precautionsThe following is a practical case, let's come together take a look.

js determines the number of occurrences of a certain character in a string

The question I encountered today is relatively simple. In order to avoid being overly ambitious, let’s write it down

<html>
<head>
<meta charset="utf-8" />
<title> js判断字符串中某字符出现的个数</title>
</head>
<body>
<script>
  var testStr = 'aoifhoiwehfoiweiwadakl';
  var i;
  var tempObj = {};
  for (i = 0; i < testStr.length; i++) {
    var charAt = testStr.charAt(i);//相当于挨个遍历字符串字符,将字符作为key,出现的次数作为value类似java中的map
    if (tempObj[charAt]) {
      tempObj[charAt]++;
    } else {
      tempObj[charAt] = 1;
    }
  }
  console.log(tempObj);
//循环遍历找到最大数
  var max = 0;//初始化一个最大数
  var maxStr;
  var obj;
  for (obj in tempObj) {
    if (tempObj[obj] > max) {
      max = tempObj[obj];
      maxStr = obj;
    }
  }
  console.log(maxStr + ':' + max);
</script>
</body>
</html>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!

Recommended reading:

How to use the JQuery framework in js

##How to use the front-end Js framework

The above is the detailed content of JS implements statistics on data patterns within strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template