The at() method translates this sentence into English.
The at() Method in ECMAScript 13
ECMAScript 13 introduced the at()
method to simplify accessing elements in arrays and strings. It supports both positive and negative indices, with negative indices counting from the end. This method provides a more intuitive syntax when working with arrays and strings.
The at() Method in Arrays
The at()
method is straightforward to use with arrays. It takes an integer argument and returns the element at the specified index. If the index is out of bounds, it returns undefined
.
const fruits = ['apple', 'banana', 'cherry', 'date'];
console.log(fruits.at(1)); // Output: 'banana'
console.log(fruits.at(-1)); // Output: 'date'
console.log(fruits.at(4)); // Output: undefined
Compared to traditional bracket notation, the at()
method offers clearer syntax when dealing with negative indices:
// Traditional way to get the last element
const lastFruit = fruits[fruits.length - 1];
// Using the at() method
const lastFruit = fruits.at(-1);
The at() Method in Strings
The at()
method also works with strings, making it easy to retrieve specific characters:
const message = 'Hello, world!';
console.log(message.at(0)); // Output: 'H'
console.log(message.at(-1)); // Output: '!'
console.log(message.at(20)); // Output: undefined
Note that the at()
method returns the UTF-16 code unit at the specified position. For characters outside the Basic Multilingual Plane (BMP), such as emojis, special handling may be required:
const emoji = '😊👍';
console.log(emoji.at(0)); // Output: '😊'
console.log(emoji.at(1)); // Output: '�' (invalid surrogate pair)
The at() Method in Typed Arrays
The at()
method is also applicable to various TypedArrays:
const intArray = new Int32Array([10, 20, 30, 40]);
console.log(intArray.at(1)); // Output: 20
console.log(intArray.at(-2)); // Output: 30
Performance Considerations
While the at()
method offers cleaner syntax, traditional bracket notation may be more efficient in performance-sensitive scenarios:
// Benchmark example
const largeArray = new Array(1000000).fill(0);
console.time('bracket notation');
for (let i = 0; i < largeArray.length; i++) {
const element = largeArray[i];
}
console.timeEnd('bracket notation');
console.time('at method');
for (let i = 0; i < largeArray.length; i++) {
const element = largeArray.at(i);
}
console.timeEnd('at method');
Browser Compatibility
The at()
method is widely supported in modern browsers but may require a polyfill for older browsers:
if (!Array.prototype.at) {
Array.prototype.at = function(index) {
// Handle negative indices
index = Math.trunc(index) || 0;
if (index < 0) index += this.length;
// Check bounds
if (index < 0 || index >= this.length) return undefined;
return this[index];
};
}
Practical Use Cases
The at()
method is particularly useful when accessing elements from the end:
// Get file extension
function getFileExtension(filename) {
const parts = filename.split('.');
return parts.at(-1);
}
console.log(getFileExtension('document.pdf')); // Output: 'pdf'
console.log(getFileExtension('archive.tar.gz')); // Output: 'gz'
console.log(getFileExtension('no_extension')); // Output: 'no_extension'
Another common use case is implementing queue or stack operations:
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
peek() {
return this.items.at(-1);
}
isEmpty() {
return this.items.length === 0;
}
}
Comparison with Other Methods
The at()
method can sometimes be interchanged with the slice()
method, but their semantics and performance differ:
const numbers = [1, 2, 3, 4, 5];
// Different ways to get the last element
const last1 = numbers.at(-1);
const last2 = numbers.slice(-1)[0];
const last3 = numbers[numbers.length - 1];
The at()
method is more direct, while slice()
creates a new array, which may impact performance with large arrays.
Handling Edge Cases
The at()
method follows the same rules as conventional array access for non-integer indices:
const arr = ['a', 'b', 'c'];
console.log(arr.at(1.5)); // Output: 'b' (index truncated to 1)
console.log(arr.at(NaN)); // Output: 'a' (NaN converted to 0)
console.log(arr.at('1')); // Output: 'b' (string '1' converted to number 1)
Combining with find() and findIndex()
The at()
method can be used alongside array search methods:
const users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
const lastActiveUserIndex = users.findIndex(user => user.active);
const lastActiveUser = users.at(lastActiveUserIndex);
Application in Functional Programming
In functional programming, at()
can be used as a pure function:
const getElementAt = (index) => (array) => array.at(index);
const getLastElement = getElementAt(-1);
const data = [10, 20, 30];
console.log(getLastElement(data)); // Output: 30
Combining with Destructuring
The at()
method can be used with destructuring to extract specific elements:
const points = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}];
const [firstPoint, , lastPoint] = [points.at(0), points.at(-1)];
console.log(firstPoint, lastPoint); // Output: {x:1,y:2} {x:5,y:6}
Usage in Asynchronous Code
The at()
method can also be used in asynchronous contexts:
async function processArray(array) {
const results = [];
for (let i = 0; i < array.length; i++) {
const current = array.at(i);
const processed = await someAsyncOperation(current);
results.push(processed);
}
return results;
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:正则表达式匹配索引
下一篇:Object.hasOwn()