簡體   English   中英

如何反轉“String.fromCodePoint”,即將字符串轉換為代碼點數組?

[英]How do I reverse `String.fromCodePoint`, i.e. convert a string to an array of code points?

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

如何將標志轉回[127482, 127480]

您正在尋找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*

或者

const array = [...theString].map(s => s.codePointAt(0));
console.log(array); // [127482, 127480]

或者像 Sebastian Simon 通過Array.from及其映射回調指出的那樣跳過一個中間步驟:

const array = Array.from(theString, s => s.codePointAt(0));
console.log(array); // [127482, 127480]

例子:

 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 和Array.from都使用字符串迭代器工作,它通過代碼點工作,而不是像大多數字符串方法那樣工作的代碼單元。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM