提示:‘字节’是存储容量的一种计量单位;英文字母及空格占用一个字节,汉字占用两个字节。
//统计一段字符串字节数
function countStrBytesLength(str){
let byteCount = 0
for(let i=0; i<str.length;i++){
if( str.charCodeAt(i) <= 255 ){
byteCount ++
}else{
byteCount += 2
}
}
return byteCount
}
const str = "hello world! 欢迎你"
const byteLen = countStrBytesLength(str)
console.log("byteLen",byteLen); //19