统计jQuery中各字符串出现次数的工具
2024-05-06 14:22:01
供稿:网友
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>工具:统计jQuery中各字符串出现次数</title>
<script src="http://demo.Vevb.com/jslib/jquery/jquery.js" type="text/javascript"></script>
</head>
<body>
<p>源文件(将jQuery源码复制到下面的文本域):</p>
<p><textarea id="myjquery" style="width: 510px; height: 250px; padding: 2px;">..</textarea></p>
<p><input id="mybtn2" style="position: relative; left: 349px;" type="button" value="统计所有字符串出现次数" /></p>
<div id="myshow2" style="width: 500px; height: 250px; border: 1px dotted #8B8D72; overflow: auto; padding: 5px;"> </div>
<p> </p>
<p><label for="myinput">字符串:<input id="myinput" type="text" /> <input id="mybtn1" style="position: relative; left: 130px;" type="button" value="统计单个字符串出现次数"
/> </label></p>
<div id="myshow1" style="width: 500px; height: 100px; border: 1px dotted #8B8D72; overflow: auto; padding: 5px;"> </div>
<p> </p>
<p>点击“统计所有字符出现次数”按钮后发现,字符串“string”竟然出现了44次,多数是诸如以下的代码</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">typeof selector === "string"
typeof data !== "string"
type === "string"
typeof context === "string"
getByName = typeof name === "string"
// ...
</pre>
</div>
<p> </p>
<p>如果使用一个变量替换,使用工具压缩时将会进一步减少文件的大小。</p>
<p> </p>
<p> </p>
<script type="text/javascript">// <![CDATA[
setTimeout(function(){
function buildRe(keywords) {
var rObj = {};
if (keywords.constructor !== Array) {
return;
}
keywords.forEach(function(it) {
rObj[it] = RegExp(''+it, 'g');
});
return rObj;
}
function count(rObj, source, callback, sortType) {
var r,
rarr,
num,
type,
func,
result = [];
var subCount = function(arr) {
var i, re, num, resu;
i = num = 0;
for (i; i<arr.length; i++) {
re = arr[i];
while( (resu=re.exec(source)) != null ) {
num++;
}
}
return num;
};
for (type in rObj) {
rarr = rObj[type];
if (rarr.constructor !== Array) {
rarr = [rarr];
}
num = subCount(rarr);
result.push({type: type, num: num});
}
// sort 0:次数顺序 1:次数倒序
if (typeof sortType !== 'undefined') {