[英]How do I reverse `String.fromCodePoint`, i.e. convert a string to an array of code points?
String.fromCodePoint(...[127482, 127480])
gives me a flag of the US (). String.fromCodePoint(...[127482, 127480])
给了我一面美国国旗 ()。
How do I turn the flag back to [127482, 127480]
?如何将标志转回
[127482, 127480]
?
You're looking for codePointAt
, perhaps using spread (etc.) to convert back to array and then mapping each of them.您正在寻找
codePointAt
,可能使用 spread (等)转换回数组,然后映射它们中的每一个。
console.log(theString.codePointAt(0)); // 127482
console.log(theString.codePointAt(2)); // 127480
// Note −−−−−−−−−−−−−−−−−−−−−−−−−−^
// It's 2 because the first code point in the string occupies two code *units*
or或者
const array = [...theString].map(s => s.codePointAt(0));
console.log(array); // [127482, 127480]
or skipping an interim step as Sebastian Simon pointed out via Array.from
and its mapping callback:或者像 Sebastian Simon 通过
Array.from
及其映射回调指出的那样跳过一个中间步骤:
const array = Array.from(theString, s => s.codePointAt(0));
console.log(array); // [127482, 127480]
Example:例子:
const theString = String.fromCodePoint(...[127482, 127480]); console.log(theString.codePointAt(0)); // 127482 console.log(theString.codePointAt(2)); // 127480 const array = [...theString].map(s => s.codePointAt(0)); console.log(array); // [127482, 127480] const array2 = Array.from(theString, s => s.codePointAt(0)); console.log(array2); // [127482, 127480]
Spread and Array.from
both work by using the strings iterator , which works by code points, not code units like most string methods do. Spread 和
Array.from
都使用字符串迭代器工作,它通过代码点工作,而不是像大多数字符串方法那样工作的代码单元。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.