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 |
瀏覽器相容性
載入中…