在 JavaScript 中获取数组的最后 N 个元素

获取数组的最后 N 个元素

Get the last N elements of an Array in JavaScript

使用该Array.slice()方法获取数组的最后 N 个元素,例如
const last3 = arr.slice(-3).

Array.slice()方法将返回一个新数组,其中包含原始数组的最后 N 个元素。

索引.js
const arr = ['a', 'b', 'c', 'd', 'e']; const last3 = arr.slice(-3); // 👉️ ['c', 'd', 'e'] console.log(last3); const last2 = arr.slice(-2); // 👉️ ['d', 'e'] console.log(last2);

我们传递给
Array.slice()
方法的唯一参数是起始索引。

传递负索引表示距数组末尾的偏移量。负索引-3意味着“给我3 数组的最后一个元素”。

这与将参数传递array.length - 3slice()
方法相同。

索引.js
const arr = ['a', 'b', 'c', 'd', 'e']; const last3 = arr.slice(-3); console.log(last3); // 👉️ ['c', 'd', 'e'] const last3Again = arr.slice(arr.length - 3); console.log(last3Again); // 👉️ ['c', 'd', 'e']

Either way, we tell the slice() method to copy the last 3 elements of the
array and place them in a new array.

The Array.slice() method doesn’t mutate the original array. It returns a new array with the copied elements (a shallow copy of a portion of the original array).

Even if we try to get more elements than the array contains, Array.slice()
won’t throw an error. Instead, it returns a new array with all elements of the
original array.

index.js
const arr = ['a', 'b', 'c']; const last100 = arr.slice(-100); console.log(last100); // 👉️ ['a', 'b', 'c']

We tried to get the last 100 elements of an array that only contains 3
elements.

In this case, all elements of the original array get copied to the new array.