编辑:根据楼主后续的评论,看起来您想要下面我列出的最后两个选项(我为教育目的而将其他选项保留在此处)。
要获取最后N个元素(我们在这些示例中使用2个),您可以选择以下选项,具体取决于您想从原始数组中删除所有其他内容、仅删除原始数组的最后N个元素还是从原始数组中复制最后N个元素。同时,这也取决于您的数组是否稀疏(您的示例似乎有点像)。
基本上,您可以使用数组操作.splice()
和.slice()
。 .splice()
会更改原始数组。.slice()
会从原始数组中复制元素。
.splice()和.slice() 的参考信息。
以下是一些选项(具体取决于您想要做什么):
// remove all elements except the last 2 from the array
stack.splice(0, stack.length -2);
或者
// return a new array of just the last two elements
// removes them from the original array too
var lastElements = stack.splice(-2, 2);
或者
// return a copy of just the first two items in the array (
// leaves original array unchanged
var lastElements = stack.slice(-2);
或者
如果你的数组是稀疏的,想要收集实际存在的最后N个元素,那么可以遍历它,收集存在的元素:
var collection = [];
for (i = stack.length - 1; i >= 0; i--) {
if (stack[i] !== undefined) {
collection.unshift(stack[i]);
if (collection.length == 2) {
break;
}
}
}
或者
如果您不需要支持IE8或者会安装一个Array.prototype.filter
的polyfill,并且只想要最后两个元素的副本,那么您可以将上一个选项简化为:
stack = stack.filter(function(item) {return item !== undefined}).slice(-2);
所有方法的演示:http://jsfiddle.net/jfriend00/f7LrA/
.filter()
中,仍然不支持IE 8,而有些人想要支持它。在我的答案中,我不会盲目地假设每个人都已经放弃了IE 8或知道填充方法。 - jfriend00