JavaScript String.fromCodePoint() 语法
String.fromCodePoint() 是 JavaScript String 对象的一个静态方法,它用于将一个或多个 Unicode 码点转换为字符串。
与 String.fromCharCode() 不同,String.fromCodePoint() 能够正确处理所有 Unicode 码点,包括 Unicode 编码点大于 “0xFFFF” 的字符(例如一些 emoji 表情)
语法:
String.fromCodePoint(num1, num2, ..., num3)说明:
String.fromCodePoint() 方法接收 0 个、1 个或多个参数。num1、num2、...、num3 等都是 Unicode 值(从 0 到 0x10FFFF)。
提示:
- String.fromCodePoint() 是 ES6 新推出的方法,我们可以把它看成是 String.fromCharCode() 的 “增强版”。
- 对于字符的 Unicode 码点,我们可以使用 codePointAt() 方法获取。
JavaScript String.fromCodePoint() 摘要
| 属于 | JavaScript String 对象 |
|---|---|
| 使用频率 | 极低 |
| 官方文档 | 查看 |
| MDN | 查看 |
JavaScript String.fromCodePoint() 示例
接下来,我们通过一个简单的例子来讲解一下 JavaScript String.fromCodePoint() 方法是如何使用的。
示例 1:String.fromCodePoint() 基本用法
const str1 = String.fromCodePoint();
console.log(str1); // (空字符串)
const str2 = String.fromCodePoint(65, 66, 67);
console.log(str2); // "ABC"
const str3 = String.fromCodePoint(20013, 22269);
console.log(str3); // "中国"运行结果如下。
(空字符串)
ABC
中国分析:
如果 String.fromCodePoint() 不接收任何参数,则其返回值为一个空字符串。
String.fromCharCode() 与 String.fromCodePoint()
String.fromCharCode() 与 String.fromCodePoint() 这两个方法的作用是一样的,都是用于将 Unicode 值转换为字符串,不过它们还是有一定的区别。
String.fromCharCode():是 ES1 的方法,它只能转换不大于 “0xFFFF” 的 Unicode 值。String.fromCodePoint():是 ES6 新推出的方法,它可以转换大于 “0xFFFF” 的 Unicode 值。
你可以将 String.fromCodePoint() 看成是 String.fromCharCode() 的 “增强版”,因此也只需要掌握 String.fromCodePoint() 即可。
示例 2:Unicode 值小于等于 “0xFFFF”
const str1 = String.fromCharCode(65, 66, 67);
console.log(str1);
const str2 = String.fromCodePoint(65, 66, 67);
console.log(str2);运行结果如下。
ABC
ABC分析:
对于小于等于 “0xFFFF” 的 Unicode 值,String.fromCharCode() 和 String.fromCodePoint() 都能正确识别。
示例 3:Unicode 值大于 “0xFFFF”
const str1 = String.fromCharCode(0x1f601);
console.log(str1);
const str2 = String.fromCodePoint(0x1f601);
console.log(str2);运行结果如下。
😁
分析:
0x1f601 是一个表示笑脸的 Unicode 值,但是它已经大于 “0xFFFF” ,因此 String.fromCharCode() 无法识别它,而 String.fromCodePoint() 却可以正确识别。
