js数组去重以及统计字符串出现最多的字符

数组去重:

<!DCOTYPE>
<html>
	<head>
		<title>数组去重</title>
		
		<script>
	function test(str){
		   let len = str.length;
		   let strtmp = [];
		   for(let i = 0;i<len;i++){
		   	   if (strtmp.indexOf(str[i])< 1){
		   	   	   strtmp.push(str[i]);
		   	   	}
		   	}
		 console.log(strtmp);
		}
		let abc = [0,2,3,5,2,1,9,3,9,1];
		test(abc);
  </script>
	</head>
	<body>

</body>
</html>

注:在判断新数组是否包含有原数组的值时,可以使用includes方法,下面的写法和上方的indexOf(str[i])<1,所起的效果是一样的。

Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。ES2016 引入了该方法。

 if (!strtmp.includes(str[i])){
		   strtmp.push(str[i]);
		   	   	}

查找字符串出现最多的:

<!DCOTYPE>
<html>
	<head>
		<title>1111</title>
		<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
		<script>
	$(function(){
		$('.btn').click(function(){
            let num = $('.num').val();
           // console.log(num);
            let len = num.length;
           let json = {};
           for (let i=0;i<len;i++){
           	     if(!json[num.charAt(i)]){
           	     	   json[num.charAt(i)]=1;
           	     	}else
           	     		{
           	     			json[num.charAt(i)]++;
           	     			}
           	}
           	let max = 0;
           	let word = '';
           	for(var i in json){
           		  if (json[i]> max){
           		  	   max = json [i];
           		  	   word = i;
           		  	}
           		}
            console.log('the word is'+word,'count is'+max);
            })
          })
  </script>
	</head>
	<body>
<label>awqewqewqewqe</label><input type="text" class="num"></input>
	<button class="btn" >22222</button>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36626755/article/details/79900420