Combining ES6 unicode literals with ES6 template literals [duplicate]

笑着哭i 提交于 2020-01-14 10:10:03

问题


If I want to print a unicode Chinese character in ES6/ES2015 javascript, I can do this:

console.log(`\u{4eb0}`);

Likewise, if I want to interpolate a variable into a template string literal, I can do this:

let x = "48b0";
console.log(`The character code is ${ x.toUpperCase() }.`);

However, it seems that I can't combine the two to print a list of, for example, 40 consecutive unicode Chinese characters. This doesn't work:

for (let i = 0, firstCharCode = parseInt("4eb0", 16); i < 40; ++i) {
    let hexCharCode = (firstCharCode + i).toString(16);
    console.log(`\u{${ hexCharCode }}`); // generates SyntaxError
}

So I'm asking if there's any way it's possible.


回答1:


You would need to use String.fromCodePoint(), which accepts a number and returns a character.

You can't do it with literals because... well... it's not a literal anymore. Literals can't be produced as the result of a procedure, they need to be written as literals.



来源:https://stackoverflow.com/questions/40155412/combining-es6-unicode-literals-with-es6-template-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!