统计字符串出现的次数
var ary = "aaaabbbccccdDDDDdfgh";
var obj = {};
var i = 0;
ary1 = ary.toLocaleLowerCase(); //将字符串转为小写
for(i = 0; i < ary1.length; i ++) {
var key = ary1[i];
if (obj[key]) {
obj[key] ++;
} else {
obj[key] = 1;
}
}
for(key in obj) {
document.write(key + "这个字母出现了" + obj[key] + "次" + "<br>")
}
let num = 0;
let char = "";
for(var val in obj) {
if (obj[val] > num) {
num = obj[val];
char = val
}
}
document.write("出现次数最多的是:" + char + "出现了:" + num + "次")
计算字符串的长度 假设:一个英文字符占用一个字节,一个中文字符占用两个字节
function getBytes(str) {
var len = str.length;
var bytes = len;
for(var i = 0; i< bytes; i++) {
if(str.charCodeAt(i) > 255) bytes ++
}
return bytes;
}
console.log(getBytes("你好,asd"))