<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
//思路:
//1.汉字占用两个字符,且在0-127范围之外
//2.判断每个字母或汉字的编码,设定一个变量num,如果在0-127内即就num+1;否则num+=2
var txt = "How old are you 博客";//20个字符
// alert(txt.length)
console.log(txt.length);
function getStringLength(str)
{
var len = 0; //数组的总长度
var num = 0; //存储每一个编码
//遍历每一个字符
for(var i = 0; i < str.length; i++)
{
num = str.charCodeAt(i);
//如果这个编码在0-127范围内,就给num+1;
if(num >= 0 && num <= 127)
{
len++;
}else
{
len+=2;
}
}
return len;
}
console.log( getStringLength(txt));
</script>
</body>
</html>