从数组中提取最后n个元素而不会干扰原始数组 [英] Extracting last n elements from array without disturbing original array
问题描述
我想从数组中提取最后n个元素而无需剪接
I want to extract last n elements from array without splice
我有如下数组,我想从新数组[33,44]中的任何数组中获取最后2个或n个元素
I have array like below , I want to get last 2 or n elements from any array in new array [33, 44]
[22, 55, 77, 88, 99, 22, 33, 44]
我试图将旧的阵列复制到新的阵列上,然后进行拼接.但是我相信还必须有其他更好的方法.
I have tried to copy old array to new array and then do splice.But i believe there must be some other better way.
var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var temp = [];
temp = arr;
temp.splice(-2);
以上代码还从原始数组 arr
;
Above code is also removing last 2 elements from original array arr
;
所以我怎么能从原始数组中提取最后n个元素而不将其转换为新变量
So how can i just extract last n elements from original array without disturning it into new variable
推荐答案
使用 slice()
代替 splice()
:
自文档:
slice()
方法将数组的一部分的浅表副本返回到从头到尾选择的新数组对象中(不包括end).原始数组将不会被修改.
The
slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var newArr = arr.slice(-2);
console.log(newArr);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于从数组中提取最后n个元素而不会干扰原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!