<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function returnByteslen(str){ //函数有了参数才能变幻无穷
var result = 0;
for (let index = 0; index < str.length; index++) {
if ( str.charCodeAt(index) <= 255 ) {
result++;
}
else{
result += 2;
}

}
return result;
}
console.log (returnByteslen("1234sarafa我"));
</script>

<script>
//或者这种方法,由于汉字字符比基础字符(为一字节)多一个字节,先直接结果设为字符串长度,再遇到汉字的时候结果加一
function returnByteslen(str){ //函数有了参数才能变幻无穷
var result = str.length;
for (let index = 0; index < str.length; index++) {
if ( str.charCodeAt(index) > 255 ) {
result += 1;
}


}
return result;
}
console.log (returnByteslen("1234sarafa我"));
</script>
</body>
</html>