我想从数组中提取最后n个元素而不需要拼接
我有下面的数组,我想从新数组中的任何数组中获取最后2个或n个元素[33,44]
[22, 55, 77, 88, 99, 22, 33, 44]
Run Code Online (Sandbox Code Playgroud)
我试图将旧数组复制到新数组然后拼接.但我相信必须有其他更好的方法.
var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var temp = [];
temp = arr;
temp.splice(-2);
Run Code Online (Sandbox Code Playgroud)
上面的代码也从原始数组中删除了最后2个元素arr;
那么我怎样才能从原始数组中提取最后n个元素而不会将其干扰为新变量
你可以使用Array#slice,它不会改变原始数组.
var array = [22, 55, 77, 88, 99, 22, 33, 44];
temp = array.slice(-2);
console.log(temp);
console.log(array);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
使用slice()而不是splice():
来自Docs:
该
slice()方法将数组的一部分的浅表副本返回到从开始到结束选择的新数组对象(不包括结束).原始数组不会被修改.
var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var newArr = arr.slice(-2);
console.log(newArr);
console.log(arr);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |