This article introduces the at function of arrays in js, which is a relatively simple knowledge popularization article and is not difficult.
0x00
First of all, we can think about the following question, if we want to get the last element of an array (this is a very common operation), what should we do? I believe most people can think of the code like this:
let last = array[ array.length - 1];
Well, this is the most common way to get the last element of an array, and so on for the second-to-last element, and similarly for the third. Of course, in addition to this way, there are other ways, such as:
let last = array.slice(-1)[0]
First get the array of the next element through slice, and then get the last element through subscript 0.
In e.g. get the last element by pop:
let last = array.pop()
However, the method of pop will change the array itself, so it is generally not recommended.
0x01
No matter the above method is tried, it feels very cumbersome. This makes people envious of the array operations in python. The last element can be obtained by negative indexing. The code is as follows:
last = array[-1]
js does not support negative indexing. However, es6 has added an at method, which can get the element of the specified index of the array, and supports negative index. Negative indices are counted from back to front, -1 for the last, -2 for the second-to-last, and so on.
So trying this method to get the last element becomes a lot easier. code show as below:
let last = array.at(-1)
0x02
If the browser does not support this method, you can Polyfill:
function at(n) {
// ToInteger() abstract op
n = Math.trunc(n) || 0;
// Allow negative indexing from the end
if (n < 0) n += this.length;
// OOB access is guaranteed to return undefined
if (n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access
return this[n];
}
const TypedArray = Reflect.getPrototypeOf(Int8Array);
for (const C of [Array, String, TypedArray]) {
Object.defineProperty(C.prototype, "at",
{ value: at,
writable: true,
enumerable: false,
configurable: true });
}
Refer to https://github.com/tc39/proposal-relative-indexing-method#polyfill
0x03
If you are interested in front-end and visualization, you can communicate with me. Follow the official account "ITMan Biao Shu" to get the author's WeChat account and receive more valuable articles in time.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。