javascript - 当数组包含基本多语言平面之外的字符时,为什么 Array#slice 无法按预期工作?

标签 javascript unicode

此代码似乎适用于“正常”字符,但不适用于基本多语言平面之外的字符。

为什么这不起作用,有没有办法让它起作用?

let s = "🚤⛵️🛥"
let unicodeArray = [...s]

console.log(unicodeArray.slice(1, 2)) // ["⛵"] // correct
console.log(unicodeArray.slice(1, 3)) // ["⛵", "️"] // incorrect

最佳答案

问题在于,在您的字符串中,⛵️ 是两个单独的代码点:帆船表情符号 (U+26F5) 和 variation selector (U+FE0F)。您的 unicodeArray 的长度为 4,因此会产生更多子字符串。

如果省略变体选择器,它将按选定的方式工作:

const s1 = "abc"
const s2 = "🚤⛵️🛥" // length 6
const s3 = "🚤⛵🛥" // length 5
console.log(s2 === s3) // false

function substrings(s) {
    const unicodeArray = Array.from(s)
    const result = []

    for (let l = 1; l <= unicodeArray.length; l++) {
      for (let i = 0; i <= unicodeArray.length - l; i++) {
        result.push(unicodeArray.slice(i, i + l).join(''))
      }
    }
    return result
}

console.log(substrings(s1)) // ["a", "b", "c", "ab", "bc", "abc"]
console.log(substrings(s2)) // ["🚤", "⛵", "️", "🛥", "🚤⛵", "⛵️", "️🛥", "🚤⛵️", "⛵️🛥", "🚤⛵️🛥"]
console.log(substrings(s3)) // ["🚤", "⛵", "🛥", "🚤⛵", "⛵️🛥", "🚤⛵️🛥"]

关于javascript - 当数组包含基本多语言平面之外的字符时,为什么 Array#slice 无法按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116410/

相关文章:

c++ - qDebug() 在 Windows 上不支持 unicode 字符串

python - 在 python 中使用 ord() 作为轮椅符号时出错

javascript - 如何仅在 URL 满足特定条件(('validate' 检查)时启用 Safari 工具栏按钮扩展?

php - 如果可能的话,我将如何从 ajax 调用中设置一个 php 数组?

javascript - 删除高亮 JavaScript getSelection 函数

javascript - 如果只有一个项目,jCarousel 什么也不显示

javascript - 当作为函数参数提供时,有没有一种方法可以在不引用对象的情况下访问对象属性?

c++ - 无法使用 CRichEditCtrl 获取带有 Unicode(包括中文)字符的文本以与 MFC 对齐

Java:从utf-8文件中读取字节

javascript - Unicode 项目符号点打印为问号