如何反转“String.fromCodePoint”,即将字符串转换为代码点数组?

ppt*_*ppt 1 javascript string codepoint unicode-string

String.fromCodePoint(...[127482, 127480])给了我一面美国国旗 ()。

如何将标志变回[127482, 127480]

T.J*_*der 5

您正在寻找codePointAt,也许使用扩展(等)将其转换回数组,然后映射它们中的每一个。

\n
console.log(theString.codePointAt(0)); // 127482\nconsole.log(theString.codePointAt(2)); // 127480\n// Note \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^\n// It\'s 2 because the first code point in the string occupies two code *units*\n
Run Code Online (Sandbox Code Playgroud)\n

或者

\n
const array = [...theString].map(s => s.codePointAt(0));\nconsole.log(array); // [127482, 127480]\n
Run Code Online (Sandbox Code Playgroud)\n

或跳过临时步骤,如Sebastian Simon通过及其映射回调指出的那样:Array.from

\n
const array = Array.from(theString, s => s.codePointAt(0));\nconsole.log(array); // [127482, 127480]\n
Run Code Online (Sandbox Code Playgroud)\n

例子:

\n

\r\n
\r\n
console.log(theString.codePointAt(0)); // 127482\nconsole.log(theString.codePointAt(2)); // 127480\n// Note \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^\n// It\'s 2 because the first code point in the string occupies two code *units*\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

Spread 和Array.from两者都通过使用字符串迭代器来工作,它通过代码点工作,而不是像大多数字符串方法那样通过代码单元工作。

\n