大网数据广告活动
Web 标准与前端开发

String.prototype.at()

· 52CE 我爱测

**`at()`** 方法接受一个整数值,并返回一个新的 String,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。

at() 方法接受一个整数值,并返回一个新的 String,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。

JavaScript Demo: String.at()

const sentence = "The quick brown fox jumps over the lazy dog.";

let index = 5;

console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of 5 returns the character u"

index = -4;

console.log(`An index of ${index} returns the character ${sentence.at(index)}`);
// Expected output: "An index of -4 returns the character d"

语法

at(index)

参数

  • index
    • : 要返回的字符串字符的索引(位置)。当传递负数时,支持从字符串末端开始的相对索引;也就是说,如果使用负数,返回的字符将从字符串的末端开始倒数。

返回值

由位于指定位置的单个 UTF-16 码元组成的 String。如果找不到指定的索引,则返回 undefined 。

示例

返回字符串的最后一个字符

以下示例提供了一个函数,该函数返回指定字符串中的最后一个字符。

// 返回给定字符串的最后一个字符的函数
function returnLast(arr) {
  return arr.at(-1);
}

let invoiceRef = "myinvoice01";

console.log(returnLast(invoiceRef));
// Logs: '1'

invoiceRef = "myinvoice02";

console.log(returnLast(invoiceRef));
// Logs: '2'

方法对比

下面我们通过比较不同的方法来实现选择 String 的倒数第二个字符。尽管以下所有方法都是有效的,但它们凸显了 at() 方法的简洁性和可读性。

const myString = "Every green bus drives fast.";

// 使用 length 属性和 charAt() 方法
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'

// 使用 slice() 方法
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'

// 使用 at() 方法
const atWay = myString.at(-2);
console.log(atWay); // 't'

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。