JavaScript使用splice按索引删除数组元素

作者:木棉时间:2026-10-29 07:25:24浏览:97

本文介绍如何在JavaScript中通过元素索引号删除数组对应元素。核心方法是使用splice(index, 1),其中index为从0开始的索引值。示例展示了如何定义函数并移除指定位置的元素,适用于需要精确控制数组内容的场景。

JavaScript使用splice按索引删除数组元素

本文介绍在JavaScript中通过元素的索引号来删除数组中对应元素的具体方法,供读者参考。

若要删除数组中指定索引的元素,例如删除第3个元素(索引为2),只需调用RemoveValByIndex(2)即可。需要注意的是,JavaScript数组的索引是从0开始计算的。


function RemoveValByIndex(arr, index) {
  arr.splice(index, 1);
}
test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';
alert("Array before removing elements: "+test);
RemoveValByIndex(test, 2);
alert("Array after removing elements: "+test);

希望上述内容对您的JavaScript程序设计有所帮助。

作者最新文章