判断一个字符串中出现次数最多的字符,并统计次数
//hash table方式 var s = ‘aaabbbcccaaabbbaaa‘; var obj = {}; var maxn = -1; var letter; for(var i = 0; i < s.length; i++) { if(obj[s[i]]) { obj[s[i]]++; if(obj[s[i]] > maxn) { maxn = obj[s[i]]; letter = s[i]; } } else { obj[s[i]] = 1; if(obj[s[i]] > maxn) { maxn = obj[s[i]]; letter = s[i]; } } } alert(letter + ‘: ‘ + maxn);
//正则方式var s = ‘aaabbbcccaaabbbaaabbbbbbbbbb‘; var a = s.split(‘‘); a.sort(); s = a.join(‘‘); var pattern = /(\w)\1*/g; var ans = s.match(pattern); ans.sort(function(a, b) { return a.length < b.length; });; console.log(ans[0][0] + ‘: ‘ + ans[0].length);
<!-- 实现一段脚本,使得点击对应链接alert出相应的编号 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <body> <a href=‘#‘> 第一个链接 </a> </br> <a href=‘#‘> 第二个链接 </a> </br> <a href=‘#‘> 第三个链接 </a> </br> <a href=‘#‘> 第四个链接 </a> </br> </body
//dom var lis = document.links; for(var i = 0, length = lis.length; i < length; i++) { lis[i].index = i; lis[i].onclick = function() { alert(this.index); }; }
//闭包 var lis = document.links; for(var i = 0, length = lis.length; i < length; i++) { (function(i) { lis[i].onclick = function() { alert(i + 1); }; })(i);
请编写一个JavaScript函数 parseQueryString,它的用途是把URL参数解析为一个对象,如: var url = “http://witmax.cn/index.php?key0=0&key1=1&key2=2″
function parseQueryString(url) { var obj = {}; var a = url.split(‘?‘); if(a.length === 1) return obj; var b = a[1].split(‘&‘); for(var i = 0, length = b.length; i < length; i++) { var c = b[i].split(‘=‘); obj[c[0]] = c[1]; } return obj; } var url = ‘http://witmax.cn/index.php?key0=0&key1=1&key2=2‘; var obj = parseQueryString(url); console.log(obj.key0, obj.key1, obj.key2); // 0 1 2
时间: 2024-10-11 09:49:19