5

javascript 字符串长度

 2 years ago
source link: https://foofish.net/JavaScript-string-unicode.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
javascript 字符串长度

Javascript中,字符串使用Unicode字符集的UTF-16编码, 通常用2个字节16位来表示一个字符。不过也有某些特字符是2个字节都没法装下的,这时候可能会用更多的字节来表示。字符串的长度 length属性是按照16位一个值来表示一个长度单位。所以对于超过两个字节的单字符,它的length就会大于1。

例如下面表情符号的长度length就是2

let s2 = "😔"  
console.log(s2.length) // 2

使用普通 for 循环遍历的时,按照16位值进行迭代。所以你会看到它输出了两个乱码字符

for(let i=0;i<s2.length;i++){
    console.log(s2[i])
}
�
�

而使用 for ... of 语法进行遍历时, 是按字符进行迭代

for(const c of s2){

    console.log(c)
}
😔

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK