提示:‘字节’是存储容量的一种计量单位;英文字母及空格占用一个字节,汉字占用两个字节。
//统计一段字符串字节数
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
文章介绍了一个JavaScript函数`countStrBytesLength`,用于计算包含英文和中文的字符串所占的字节数。函数通过遍历字符串并检查每个字符的Unicode码值来确定其占用的字节数,英文字符占1字节,汉字占2字节。示例中,字符串`helloworld!欢迎你`的字节数为19。
516

被折叠的 条评论
为什么被折叠?



