此代码似乎适用于“正常”字符,但不适用于基本多语言平面之外的字符。
为什么这不起作用,有没有办法让它起作用?
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/