String.prototype.charAt()
charAt() 方法用于返回由给定索引处的单个 UTF-16 码单元组成的新字符串。
charAt() 始终将字符串视为 UTF-16 码单元序列进行索引,因此它可能会返回孤立的代理码元。要获取给定索引处的完整 Unicode 码点,请使用 String.prototype.codePointAt() 和 String.fromCodePoint()。
试一试
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"
语法
charAt(index)
参数
返回值
一个字符串,表示指定 index 处的字符(恰好一个 UTF-16 码单元)。如果 index 超出了 0 – str.length - 1 的范围,charAt() 将返回一个空字符串。
描述
字符串中的字符从左到右索引。第一个字符的索引是 0,名为 str 的字符串中最后一个字符的索引是 str.length - 1。
Unicode 码点范围从 0 到 1114111 (0x10FFFF)。charAt() 总是返回一个值小于 65536 的字符,因为较高的码点由一对 16 位代理伪字符表示。因此,为了获取值大于 65535 的完整字符,有必要检索 charAt(i) 和 charAt(i + 1)(就好像处理一个有两个字符的字符串一样),或者改用 codePointAt(i) 和 String.fromCodePoint()。有关 Unicode 的信息,请参阅 UTF-16 字符、Unicode 码点和图素簇。
charAt() 与使用 方括号表示法在指定索引处访问字符非常相似。主要区别在于:
charAt()尝试将index转换为整数,而方括号表示法则不转换,直接将index用作属性名。- 如果
index超出范围,charAt()返回一个空字符串,而方括号表示法返回undefined。
示例
使用 charAt()
以下示例显示了字符串 "Brave new world" 中不同位置的字符。
const anyString = "Brave new world";
console.log(`The character at index 0 is '${anyString.charAt()}'`);
// No index was provided, used 0 as default
console.log(`The character at index 0 is '${anyString.charAt(0)}'`);
console.log(`The character at index 1 is '${anyString.charAt(1)}'`);
console.log(`The character at index 2 is '${anyString.charAt(2)}'`);
console.log(`The character at index 3 is '${anyString.charAt(3)}'`);
console.log(`The character at index 4 is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
这些行显示以下内容:
The character at index 0 is 'B' The character at index 0 is 'B' The character at index 1 is 'r' The character at index 2 is 'a' The character at index 3 is 'v' The character at index 4 is 'e' The character at index 999 is ''
charAt() 可能会返回孤立的代理码元,它们不是有效的 Unicode 字符。
const str = "𠮷𠮾";
console.log(str.charAt(0)); // "\ud842", which is not a valid Unicode character
console.log(str.charAt(1)); // "\udfb7", which is not a valid Unicode character
要获取给定索引处的完整 Unicode 码点,请使用按 Unicode 码点拆分的索引方法,例如 String.prototype.codePointAt() 和 将字符串展开为 Unicode 码点数组。
const str = "𠮷𠮾";
console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷"
console.log([...str][0]); // "𠮷"
注意: 避免使用 charAt() 重新实现上述解决方案。孤立代理码元的检测及其配对非常复杂,并且内置 API 可能更高效,因为它们直接使用字符串的内部表示。如有必要,请为上述 API 安装 polyfill。
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.charat |
浏览器兼容性
加载中…