在 javascript 数组中,如何获取最后 5 个元素,不包括第一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6473858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In a javascript array, how do I get the last 5 elements, excluding the first element?
提问by TIMEX
[1, 55, 77, 88] // ...would return [55, 77, 88]
adding additional examples:
添加其他示例:
[1, 55, 77, 88, 99, 22, 33, 44] // ...would return [88, 99, 22, 33, 44]
[1] // ...would return []
回答by SLaks
You can call:
您可以致电:
arr.slice(Math.max(arr.length - 5, 1))
If you don't want to exclude the first element, use
如果您不想排除第一个元素,请使用
arr.slice(Math.max(arr.length - 5, 0))
回答by Belldandu
Here is one I haven't seen that's even shorter
这是我从未见过的更短的
arr.slice(1).slice(-5)
arr.slice(1).slice(-5)
Run the code snippet below for proof of it doing what you want
运行下面的代码片段以证明它做你想做的事
var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],
arr2 = [0, 1, 2, 3];
document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);
Another way to do it would be using lodash https://lodash.com/docs#rest- that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.
另一种方法是使用 lodash https://lodash.com/docs#rest- 当然,如果您不介意在尝试从浏览器中加载一个巨大的 javascript 缩小文件时。
_.slice(_.rest(arr), -5)
_.slice(_.rest(arr), -5)
回答by hhsadiq
回答by Arka
Try this:
尝试这个:
var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
array_last_five.shift();
}
回答by Madhu Kumar
var y = [1,2,3,4,5,6,7,8,9,10];
console.log(y.slice((y.length - 5), y.length))
you can do this!
你可以这样做!
回答by godblessstrawberry
ES6 way:
ES6方式:
I use destructuring assignmentfor array to get first
and remaining rest
elements and then I'll take last five of the rest
with slicemethod:
我使用数组的解构赋值来获取first
和剩余rest
元素,然后我将使用rest
with slice方法的最后五个:
const cutOffFirstAndLastFive = (array) => {
const [first, ...rest] = array;
return rest.slice(-5);
}
cutOffFirstAndLastFive([1, 55, 77, 88]);
console.log(
'Tests:',
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),
JSON.stringify(cutOffFirstAndLastFive([1]))
);