JavaScript - Unicode
什么是 Unicode?h2>
Unicode 是一个通用字符集,包含来自大多数语言、书写系统等的字符列表。它为每个字符提供一个唯一的编号,而不关注编程语言、平台、操作系统等。此外,它还包括标点符号、表情符号、特殊字符等。
简而言之,Unicode 集包含唯一的编号,每个编号代表一个唯一的字符,无论平台、操作系统等如何,它们的含义都相同。
Unicode 背后的直觉
在理解 Unicode 之前,让我们先了解一下它背后的想法。你能回答为什么你能够阅读本教程吗?嗯,因为你知道所写字母的含义。读者(你)和作者对英文字母的理解是相同的;这就是为什么你能够读懂作者写的内容。
同样,计算机也不理解字母。对于计算机来说,字母是位序列,每个序列都映射到一个唯一的字符,称为 Unicode。
现在,让我们深入了解 Unicode。
JavaScript 中的 Unicode
JavaScript 允许开发者在字符串字面量和源代码中使用 Unicode 字符。开发者需要使用转义符号 (\u) 才能在 JavaScript 代码中使用 Unicode 字符。
语法
用户可以按照以下语法在 JavaScript 中使用 Unicode 字符。
const char = '\uxxxx';
在上述语法中,"\uxxxx"是一个 Unicode 字符。这里,"xxxx"代表十六进制字符,"/u"代表转义符号。
示例
示例:Unicode 转义序列
在下面的示例中,我们使用 Unicode 转义序列打印了"hello"消息。
<html>
<body>
<div>Using unicode escape sequence</div>
<div id = "output"> </div>
<script>
let str = '\u0068\u0065\u006c\u006c\u006f'
document.getElementById("output").innerHTML = str;
</script>
</body>
</html>
输出
Using unicode escape sequence hello
示例:在变量名中使用 Unicode 字符
在下面的代码中,我们使用了两个不同的 Unicode 字符作为两个不同的标识符(变量名)。在输出中,您可以观察到两个标识符的值。
<html>
<body>
<div>Using unicode characters in variable names</div>
<div id = "output"> </div>
<script>
// Using the Unicode characters in variable names
let \u0061 = "Hello";
let \u0062 = "World";
document.getElementById("output").innerHTML = a + " " + b;
</script>
</body>
</html>
输出
Using unicode characters in variable names Hello World
示例:在字符串中使用 Unicode 字符
在此示例中,我们在字符串字面量中使用了 Unicode 字符。输出显示了字符串中间的特殊字符。
<html>
<body>
<div> Using the Unicode Characters in String </div>
<div id = "output"> </div>
<script>
// 使用字符串中的 Unicode 字符
let str = 'Hello \u00D8 \u00F8 World';
document.getElementById("output").innerHTML = str;
</script>
</body>
</html>
输出
Using the Unicode Characters in String Hello World
示例:使用 Unicode 表示非 BMP(基本多文种平面)字符
在下面的示例中,我们使用 Unicode 字符(代码点)来显示非 BMP(基本多文种平面)字符。我们以一位医护人员为例进行了演示。
<html>
<body>
<div>showing person heath worker using unicode code point</div>
<div id = "output"> </div>
<script>
// 使用 Unicode 字符显示表情符号
const smileyFace = '\u{1F9D1}\u200D\u2695\uFE0F';
document.getElementById("output").innerHTML = smileyFace;
</script>
</body>
</html>
输出
showing person heath worker using unicode code point
示例:使用 Unicode 字符显示表情符号
在下面的代码中,我们使用 Unicode 字符来显示笑脸表情符号。
<html>
<body>
<div>Showing Emojies Using the Unicode Characters </div>
<div id = "output"> </div>
<script>
// 使用 Unicode 字符显示表情符号
const smileyFace = '\uD83D\uDE0A';
document.getElementById("output").innerHTML = smileyFace;
</script>
</body>
</html>
输出
Showing Emojies Using the Unicode Characters
正如我们所见,每个 Unicode 字符代表一个唯一的字符。在 JavaScript 中,我们可以将 Unicode 字符与标识符、字符串字面量等一起使用。

