String.prototype.at()
String
值的 at()
方法采用整数值并返回由位于指定偏移处的单个 UTF-16 代码单元组成的新 String
。此方法允许正整数和负整数。负整数从最后一个字符串字符开始倒数。
¥The at()
method of String
values takes an integer value and returns a new String
consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.
Try it
语法
参数
返回值
示例
返回字符串的最后一个字符
¥Return the last character of a string
以下示例提供了一个函数,该函数返回在指定字符串中找到的最后一个字符。
¥The following example provides a function which returns the last character found in a specified string.
// A function which returns the last character of a given string
function returnLast(arr) {
return arr.at(-1);
}
let invoiceRef = "myinvoice01";
console.log(returnLast(invoiceRef)); // '1'
invoiceRef = "myinvoice02";
console.log(returnLast(invoiceRef)); // '2'
比较方法
¥Comparing methods
在这里,我们比较选择 String
的倒数第二个(最后一个)字符的不同方法。虽然以下所有方法都是有效的,但它强调了 at()
方法的简洁性和可读性。
¥Here we compare different ways to select the penultimate (last but one) character of a String
. Whilst all below methods are valid, it highlights the succinctness and readability of the at()
method.
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'
规范
Specification |
---|
ECMAScript Language Specification # sec-string.prototype.at |
浏览器兼容性
BCD tables only load in the browser