fromCodePoint() 方法通过给定的 Unicode 代码点序列创建一个字符串。
示例
// returns a string of characters represented by unicode 65, 66 and 67
let alphabets = String.fromCodePoint(65, 66, 67);
// printing the equivalent characters
console.log(alphabets);
// Output:
// ABC
fromCodePoint() 语法
fromCodePoint() 方法的语法是:
String.fromCodePoint(num1, ..., numN)
fromCodePoint() 方法是一个静态方法,通过 String 类名调用。
fromCodePoint() 参数
fromCodePoint() 方法接受:
- num1, ..., numN - 代码点序列。
fromCodePoint() 返回值
- 返回一个由指定的 Unicode 代码点序列创建的字符串。
注意事项:
- Unicode 代码点值是每个字符根据国际标准定义的一个数值。例如,字母 A 的 Unicode 值为 65。
- 如果给出了无效的 Unicode 代码点,该方法将抛出
RangeError。
示例 1:使用 fromCodePoint() 方法
// return 'Hello' string from given unicode
let greet = String.fromCodePoint(72, 101, 108, 108, 111);
// printing the equivalent characters
console.log(greet);
输出
Hello
在上面的例子中,我们通过 String 构造函数对象调用了 fromCodePoint(),并将返回值赋给了 greet。
fromCodePoint() 方法将给定的 Unicode 代码点转换的字符连接起来。
也就是说,Unicode 代码点 72 被转换为 "H",101 被转换为 "E",108 被转换为 "L",111 被转换为 "O",随后连接成 "Hello" 字符串。
示例 2:fromCodePoint() 与十六进制值
// passing unicode as a hexadecimal value
let string2 = String.fromCodePoint(0x2014);
console.log(string2);
输出
—
在上面的例子中,我们传递了一个十六进制值 0x2014,其十进制等效值为 8212。Unicode 代码点值 8212 被转换为字符 —。
string2 持有 fromCodePoint(0x2014) 的返回值,即 —。
示例 3:fromCodePoint() 与无效的 Unicode 代码点
// passing invalid unicode value
let string3 = String.fromCodePoint(Infinity);
console.log(string3);
输出
RangeError: Invalid code point Infinity
另请阅读