Get the last two positions of an array [duplicate]

天涯浪子 提交于 2019-12-13 07:01:05

问题


I would like to know how can I obtain the last two elements of this array like this:

array = [1,5,7,8,10,12,23,24];

I am trying to obtain with slice() function but it doesn´t work for me, beacuse I always I want to obtain the last two positions.

array = [23,24];

I hope that anyone can help me in this question.

Regards!


回答1:


Use Array#slice with negative index.

var array = [1,5,7,8,10,12,23,24];

console.log(array.slice(-2));

You can learn more about this method also here.




回答2:


array = [1,5,7,8,10,12,23,24];


console.log(array.slice(-2))

Use slice -2




回答3:


aray.prototype.splice() also

Note: Splice it will update the original array also

var array = [1,5,7,8,10,12,23,24];

console.log(array.splice(-2));


来源:https://stackoverflow.com/questions/42368587/get-the-last-two-positions-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!