如果我在JavaScript中有数组,如何从中删除最后n个项并将其作为新数组返回?
我有两个选项,拼接或迭代弹出/推送。哪个更好?
谢谢
答案 0 :(得分:3)
你应该拼接它:
array.splice(array.length-n, array.length);
因此:
function removeLast(arr, n){
arr.splice(arr.length-n, arr.length);
return arr;
}
arr = JSON.parse(prompt("Enter the array"));
n = parseInt(prompt("Enter the number of elements you want to remove"), 10);
alert(removeLast(arr, n));
> removeLast([1, 2, 3, 4, 5], 3)
[1, 2]
> removeLast([1, 2, 3, 4, 5], 2)
[1, 2, 3]
> removeLast([1, 2, 3, 4, 5], 1)
[1, 2, 3, 4]
答案 1 :(得分:0)