JavaScript String fromCharCode()

fromCharCode() 方法根据指定的 UTF-16 代码单元序列返回一个创建的 字符串

示例

// use of fromCharCode() let string1 = String.fromCharCode(72, 69, 76, 76, 79);
// printing the equivalent characters console.log(string1); // Output: // HELLO

fromCharCode() 语法

fromCharCode() 方法的语法是

String.fromCharCode(num1, ..., numN)

fromCharCode() 方法是一个静态方法,使用 String 类名调用。


fromCharCode() 参数

fromCharCode() 方法接受

  • num1, ..., numN - 一系列 UTF-16 代码单元(介于 **0** 和 **65535** 之间的数字)。大于 65535 (0xFFFF) 的数字将被截断。

fromCharCode() 返回值

  • 返回一个长度为 N 的字符串,包含指定的 N 个 UTF-16 代码单元。

注意fromCharCode() 方法返回的是一个字符串,而不是一个 String 对象。


示例 1:使用 fromCharCode() 方法

// use of fromCharCode() let string1 = String.fromCharCode(72, 69, 76, 76, 79);
// printing the equivalent characters console.log(string1);

输出

HELLO

在上面的示例中,我们通过 String 构造函数对象调用了 fromCharCode() 方法,并将其赋值给 string1 变量。

fromCharCode() 会将给定的 UTF-16 代码单元转换来的字符连接起来。也就是说,unicode 值 **72** 被转换为 H,**69** 转换为 E,**76** 转换为 L,**79** 转换为 O,最后连接成字符串 HELLO


示例 2:使用 fromCodePoint() 方法和十六进制值

// numbers can be passed as a hexadecimal value let string2 = String.fromCharCode(0x2017);
console.log(string2);

输出

在上面的示例中,我们传入了一个十六进制值 0x2017,其十进制等价值为 **8215**。unicode 点值 **8215** 被转换为字符

string2 存储了 fromCharCode(0x2017) 的返回值,即

注意: 如果任何 unicode 值无法用单个 UTF-16 代码单元表示,我们可以使用 fromCodePoint() 方法。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战