gpt4 book ai didi

javascript - 从数组 JavaScript 中删除并返回最后 n 项的最快方法

转载 作者:行者123 更新时间:2023-11-28 15:25:14 26 4
gpt4 key购买 nike

如果我在 JavaScript 中有一个数组,如何从中删除最后 n 个项目并将其作为新数组返回?

我有两个选择,拼接或迭代弹出/推送。哪个更好?

谢谢

最佳答案

你应该拼接它:

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]

关于javascript - 从数组 JavaScript 中删除并返回最后 n 项的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com