let str = "hello世界";
console.log(str.length)//7
如何计算所占用的字节数呢?
function getByteLength(str) { let length = 0; for (let i = 0; i < str.length; i++) { let charCode = str.charCodeAt(i); if ((charCode >= 0x0001 && charCode <= 0x007F) || (charCode >= 0x02B9 && charCode <= 0x036F)) { length += 1; } else { length += 2; } } return length;
}
let str = "hello世界";
console.log(getByteLength(str))//9
可能你会遇到这种类似的需求,可以用到