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

语法

¥Syntax

js
at(index)

参数

¥Parameters

index

要返回的字符串字符的索引(位置)。当传递负索引时,支持从字符串末尾开始相对索引;即,如果使用负数,则将从字符串末尾倒数找到返回的字符。

返回值

¥Return value

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

¥A String consisting of the single UTF-16 code unit located at the specified position. Returns undefined if the given index can not be found.

示例

¥Examples

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

¥Return the last character of a string

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

¥The following example provides a function which returns the last character found in a specified string.

js
// 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.

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'

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.at

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看