String.prototype.at()
String 值的 at() 方法接受一个整数值,并返回一个由位于指定偏移量的单个 UTF-16 码单元组成的新 String。此方法支持正数和负数整数。负整数从字符串的最后一个字符开始倒数。
试一试
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"
语法
js
at(index)
参数
index-
要返回的字符串字符的索引(位置)。当使用负索引时,支持从字符串末尾进行相对索引;即,如果使用负数,则返回的字符将通过从字符串末尾开始倒数来找到。
返回值
一个由位于指定位置的单个 UTF-16 码单元组成的 String。如果找不到给定的索引,则返回 undefined。
示例
返回字符串的最后一个字符
以下示例提供了一个函数,该函数返回在指定字符串中找到的最后一个字符。
js
// A function which returns the last character of a given string
function returnLast(str) {
return str.at(-1);
}
let invoiceRef = "my-invoice01";
console.log(returnLast(invoiceRef)); // '1'
invoiceRef = "my-invoice02";
console.log(returnLast(invoiceRef)); // '2'
比较方法
这里我们比较选择 String 的倒数第二个(倒数第一个之前的)字符的不同方法。尽管以下所有方法都是有效的,但它突出了 at() 方法的简洁性和可读性。
js
const myString = "Every green bus drives fast.";
// Using length property and charAt() method
const lengthWay = myString.charAt(myString.length - 2);
console.log(lengthWay); // 't'
// Using slice() method
const sliceWay = myString.slice(-2, -1);
console.log(sliceWay); // 't'
// Using at() method
const atWay = myString.at(-2);
console.log(atWay); // 't'
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.at |
浏览器兼容性
加载中…