javascript 如何从数组中删除除最后 N 个元素之外的所有元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18277603/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:18:11  来源:igfitidea点击:

How can I remove all but the last N elements from an array?

javascript

提问by titans

I have an array. I have a variable that shows how many elements in the array must be left at the end. Is there a function that would do that? Example:

我有一个数组。我有一个变量,显示数组中最后必须保留多少个元素。有没有一个功能可以做到这一点?例子:

var arr = [1, 2, 3, 4, 5];
var n = 2;
arr = someFunction(n); // arr = [4, 5];

I want an array with the last nelements in it.

我想要一个包含最后一个n元素的数组。

回答by Craig

The slice method is what you want. It returns a new object, so you must replace your existing object with the new one.

slice 方法就是你想要的。它返回一个新对象,因此您必须用新对象替换现有对象。

arr = arr.slice(-1 * n);

Alternatively, modify the existing array with splice().

或者,使用splice().

arr.splice(0, arr.length - n);

Splice is the more efficient, since it is not copying elements.

Splice 效率更高,因为它不复制元素。