You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:使用splice删除数组最后两个元素仅删一个,如何解决?

数组splice方法删除末尾两个元素的正确用法

先看你写的代码:

const arr2 = ["one" , "two" , "three"];

const removedElements = arr2.splice(-1 , 2 , "four" , "five");

console.log(arr2 , removedElements)

你遇到的问题是只删除了一个元素,原因很直接:splice(-1, 2)的起始位置是数组最后一个元素(对应值"three"),但原数组总共只有3个元素,从这个位置往后最多只能删掉1个元素,所以实际只移除了"three";同时你还在该位置插入了"four"和"five",最终数组会变成["one", "two", "four", "five"],删除的元素数组是["three"]。

要正确删除数组最后两个元素,有两种常用写法:

方法一:从倒数第二个位置开始删除2个元素

const arr2 = ["one", "two", "three"];
const removedElements = arr2.splice(-2, 2);
console.log(arr2, removedElements); // 输出: ["one"] ["two", "three"]

这里-2指向数组倒数第二个元素(即"two"),从这个位置开始删除2个元素,刚好覆盖最后两个元素。

方法二:通过数组长度计算起始位置

const arr2 = ["one", "two", "three"];
const removedElements = arr2.splice(arr2.length - 2, 2);
console.log(arr2, removedElements); // 输出: ["one"] ["two", "three"]

数组长度是3,arr2.length - 2得到索引1(对应"two"),从这个索引开始删除2个元素,效果和方法一完全一致。

注意:如果不需要在删除位置插入新元素,就不要加splice的第三个及以后参数,否则这些元素会被插入到数组中。

内容的提问来源于stack exchange,提问作者kishore pantra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:18:43