JavaScript 汉字字符串占一个长度问题解决

const str = '你好,世界!';
const length = Array.from(str).reduce((acc, cur) => acc + (cur.charCodeAt(0) > 255 ? 2 : 1), 0);
console.log(length); // Output: 7

在JavaScript中 字符串使用length ,存在汉字会导致字符串的长度 不准。使用循环,通过charCodeAt()方法把单个字符转成Unicode字符来判断。

 

posted @ 2023-03-23 14:30  微风吹过~  阅读(31)  评论(0编辑  收藏  举报