【问题标题】:Why does Array#slice not work as expected when an array contains characters outside the Basic Multilingual Plane?当数组包含基本多语言平面之外的字符时,为什么 Array#slice 不能按预期工作?
【发布时间】:2020-05-23 18:21:39
【问题描述】:

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

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

let s = "????⛵️????"
let unicodeArray = [...s]

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

【问题讨论】:

  • JavaScript 用 UTF-16 表示 Unicode,大部分字符串操作不明白其含义。
  • 很好。但我故意使用扩展语法以 BMP 感知方式创建数组。破损在哪里?
  • 第二个和第三个符号之间的“空”字符是问题

标签: javascript unicode


【解决方案1】:

问题在于,在您的字符串中,⛵️ 是两个独立的代码点:帆船表情符号 (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)) // ["?", "⛵", "?", "?⛵", "⛵️?", "?⛵️?"]

【讨论】:

【解决方案2】:

因为这些字符的长度会混淆您的功能

console.log("?⛵️?".length); // 6
console.log("abc".length);     // 3

【讨论】:

  • 为什么?我以符合 BMP 的方式 ([...s]) 将字符串拆分为字符。我没有提到字符串的长度。故意的。
  • 您在编辑帖子之前确实提到了长度。我可以看到编辑历史...
  • 是的...你用字符串制作的数组...[...s]
  • 别闹了。无论如何,那个字符串不是有问题的字符串,所以......我什至不明白球门柱是如何移动到那里的。
  • 很高兴您现在可以看到您犯的错误。很好的交谈
猜你喜欢
  • 1970-01-01
  • 2018-01-22
  • 2016-07-29
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2011-05-01
相关资源
最近更新 更多