题解 | #获取字符串的长度#
获取字符串的长度
https://www.nowcoder.com/practice/e436bbc408744b73b69a8925fac26efc
基于 arr 的方法,代码我就不压缩了
function strLength(s = '', bUnicode255For1 = true) {
let length = s.length;
if (!bUnicode255For1) {
length = s
.split('') // 拆分
.map(e => e
.charCodeAt(0) // 获取unicode编码
.toString(16) // 转换HEX(16进制)字符串
.length / 2) // HEX字符串长度 ÷ 2,获得e的字节长度
.reduce((acc, current) => acc + current, 0) // 字节长度累加
}
return length;
}
韶音科技公司氛围 647人发布
