JS字符串用法总结
字符串是JavaScript的一种基本的数据类型。 01.创建字符串 09.函数值传递说明
10.计算字符串的字节长度
我们知道Javascript使用Unicode编码,在实际使用中常见的实现方案有UTF-8和UTF-16,我们看下在这种编码方式下怎样获取字符串所占用的字节长度。
参考文档
1.http://www.w3school.com.cn/js/js_obj_string.asp
2.http://www.w3school.com.cn/jsref/jsref_obj_string.asp 3.http://blog.sina.com.cn/s/blog_7dfe67db0100v9om.html
//当作为函数参数传递时,传递原字符串的副本
var str = "demoFunc";
function demoFunc(str) {
//str作为传入的字符串类型,函数内操作原字符串副本,不修改原字符串
str = "innerDemoFunc"; //str:"innerDemoFunc"
}
demoFunc(str); //str:"demoFunc"
//方法一:
String.prototype.getBytesLength = function() {
var totalLength = 0;
var charCode;
for (var i = 0; i < this.length; i++) {
charCode = this.charCodeAt(i);
if (charCode < 0x007f) {
totalLength++;
} else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
totalLength += 2;
} else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
totalLength += 3;
} else{
totalLength += 4;
}
}
return totalLength;
}
var str="我的测试程序Demo";
console.log("字符数:", str.length, "字节数:", str.getBytesLength());
2.http://www.w3school.com.cn/jsref/jsref_obj_string.asp 3.http://blog.sina.com.cn/s/blog_7dfe67db0100v9om.html

浙公网安备 33010602011771号