先上代码:
function strCode(str) { //获取字符串的字节数
var count = 0; //初始化字节数递加变量并获取字符串参数的字符个数
if (str) { //如果存在字符串,则执行
len = str.length;
for (var i = 0; i < len; i++) { //遍历字符串,枚举每个字符
if (str.charCodeAt(i) > 255) { //字符编码大于255,说明是双字节字符(即是中文)
count += 2; //则累加2个
} else {
count++; //否则递加一次
}
}
console.log(count);
return count; //返回字节数
} else {
console.log(0);
return 0; //如果参数为空,则返回0个
}
}
var a = '1234567';
var c = '我是第一';
strCode(a);
strCode();
strCode(c);
strCode('asd啊啊啊');
效果如下:
解析:
charCodeAt()
charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。 字符串中第一个字符的位置为 0, 第二个字符位置为 1,以此类推。
语法:
string.charCodeAt(index)
参数值:
参数 | 描述 |
---|---|
index | 必需。表示字符串中某个位置的数字,即字符在字符串中的下标 |
返回值:
类型 | 描述 |
---|---|
Number | 返回在指定的位置的字符的 Unicode 编码 |
例子:
var a = '1x.我'
console.log(a.charCodeAt(0));
console.log(a.charCodeAt(1));
console.log(a.charCodeAt(2));
console.log(a.charCodeAt(3));
效果:
注:当unicode>255,可以判断该字符字节长度为2(中文)
参考:http://c.biancheng.net/view/5547.html