javascript - 为什么 '❌' [0] === '❌' 但 '✔️' [0] !== '✔️' ?

标签 javascript string unicode

'❌'[0] === '❌' // true
'✔️'[0] === '✔️' // false
'✔️'[0] === '✔'  // true

我怀疑它与 unicode 相关,但想准确了解正在发生的事情以及如何正确比较这些字符。为什么“✔️”与“❌”的处理方式不同?

我在这个简单的字符计数中遇到过

'✔️❌✔️❌'.split('').filter(e => e === '❌').length // 2
'✔️❌✔️❌'.split('').filter(e => e === '✔️').length // 0

最佳答案

因为 ✔️ 需要两个字符: "✔️".length === 2

"✔️"[0] === "✔" 我认为 "✔️"[1] 表示颜色。

"❌".length === 1 所以它只需要一个字符。

这类似于具有不同肤色的表情符号的工作方式。

至于如何比较,我认为 "✔️".codePointAt(0)(不要与 charCodeAt() 混淆)可能会有所帮助。参见 https://thekevinscott.com/emojis-in-javascript/ :

codePointAt and fromCodePoint are new methods introduced in ES2015 that can handle unicode characters whose UTF-16 encoding is greater than 16 bits, which includes emojis. Use these instead of charCodeAt, which doesn’t handle emoji correctly.

关于javascript - 为什么 '❌' [0] === '❌' 但 '✔️' [0] !== '✔️' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69548147/

相关文章:

javascript - VueJS : How to prevent textarea default behavior

javascript - JS 后缀操作中的左侧表达式无效?

关于字符串操作的 Java 问题 - 反转文本将 "null"添加到末尾

python - 如何打印 unicode 字符串的十进制表示形式?

c# - 将unicode格式的表情字符串转换为单字符表情字符串

加载 Excel 对话框时,Javascript 隐藏 div

javascript - 带有 Ruby on Rails 的 Google Charts API

c - 如何用C语言从字符串中按数字分隔单词

从字符串中删除第 n 个空格

html - 在适当的支持下使用中点 ASCII?