在JavaScript数组中,我如何得到最后5个元素,不包括第一个元素?

[1, 55, 77, 88] // ...would return [55, 77, 88]

再举几个例子:

[1, 55, 77, 88, 99, 22, 33, 44] // ...would return [88, 99, 22, 33, 44]

[1] // ...would return []

当前回答

var y = [1,2,3,4,5,6,7,8,9,10]; console.log(y.slice((y.length - 5), y.length))

你能做到的!

其他回答

如果你正在使用lodash,它甚至更简单的takeRight。

_。takeRight(加勒比海盗5);

ES6道:

我使用解构赋值数组来获得第一个和剩余的其余元素,然后我将使用slice方法获取剩余的最后五个元素:

const cutOffFirstAndLastFive = (array) => { Const[首先,…Rest] =数组; 返回rest.slice (5); } cutOffFirstAndLastFive([1,55,77,88]); console.log ( “测试:”, JSON。stringify(cutOffFirstAndLastFive([1,55,77,88])), JSON。stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])), JSON.stringify (cutOffFirstAndLastFive ([1])) );

我还没见过比这更短的

arr.slice(1).slice(-5)

运行下面的代码片段,以证明它正在执行您想要的操作

Const arr = []; 对于(设I = 0;I < 8;我+ +){ arr.push(我); console.log('数组$ {i + 1}: $ {arr} - > $ {arr.slice (1) .slice(5)}”); }

另一种方法是使用lodash https://lodash.com/docs#rest -当然,如果您不介意从浏览器中加载一个巨大的JavaScript缩小文件的话。

_.slice(_.rest(arr), -5)
array.reverse()
     .slice(0,5)
     .reverse()  //if you wanna keep the order of last 5

const myOriginalArray = [...Array(10).keys()] //making an array of numbers

const instanceFromlastFiveItemsOfMyArray = [
    ...myOriginalArray.reverse().slice(0,5).reverse()
    ]

你可以像这样在一行中完成:

Const y = [1,2,3,4,5,6,7,8,9,10]; const lastX = 5; Const res = y.filter((val, index, arr) => index > arr。长度- lastX - 1); console.log (res);

.filter((val, index, arr) => index > arr.length - 6)