Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. String
  6. String.prototype.charAt()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

String.prototype.charAt()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.

StringcharAt() 方法返回一个由给定索引处的单个 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"

语法

js
charAt(index)

参数

index

要返回的字符的索引,从零开始。会被转换为整数——undefined 会被转换为 0。

返回值

返回一个字符串,该字符串表示指定index 处的字符(恰好是一个 UTF-16 码元)。如果index 超出了0str.length - 1 的范围,charAt() 将返回一个空字符串。

描述

字符串中的字符从左到右进行索引。第一个字符的索引为0,字符串中最后一个字符的索引为str.length - 1

Unicode 码位的范围从01114111 (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" 不同位置处的字符:

js
const anyString = "Brave new world";console.log(`在索引 0 处的字符为 '${anyString.charAt()}'`);// 没有提供索引,使用 0 作为默认值console.log(`在索引 0 处的字符为 '${anyString.charAt(0)}'`);console.log(`在索引 1 处的字符为 '${anyString.charAt(1)}'`);console.log(`在索引 2 处的字符为 '${anyString.charAt(2)}'`);console.log(`在索引 3 处的字符为 '${anyString.charAt(3)}'`);console.log(`在索引 4 处的字符为 '${anyString.charAt(4)}'`);console.log(`在索引 999 处的字符为 '${anyString.charAt(999)}'`);

上面代码的输出为:

在索引 0 处的字符为 'B'在索引 0 处的字符为 'B'在索引 1 处的字符为 'r'在索引 2 处的字符为 'a'在索引 3 处的字符为 'v'在索引 4 处的字符为 'e'在索引 999 处的字符为 ''

charAt() 可能会返回孤项代理,这些代理项不是有效的 Unicode 字符。

js
const str = "𠮷𠮾";console.log(str.charAt(0)); // "\ud842",这不是有效的 Unicode 字符console.log(str.charAt(1)); // "\udfb7",这不是有效的 Unicode 字符

要获取给定索引处的完整 Unicode 码位,请使用按 Unicode 码位拆分的索引方法,例如String.prototype.codePointAt() 和将字符串展开为 Unicode 码位数组

js
const str = "𠮷𠮾";console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷"console.log([...str][0]); // "𠮷"

备注:避免使用charAt() 重新实现上述解决方案。检测孤项代理及其配对很复杂,而内置 API 可能更高效,因为它们直接使用字符串的内部表示形式。如有必要,请安装上述 API 的 polyfill。

规范

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.charat

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp