如何使用JavaScript按索引删除数组元素?

62 浏览
0 Comments

如何使用JavaScript按索引删除数组元素?

这个问题已经有答案了
如何在JavaScript中删除数组中的特定项?

此帖子已编辑并提交审核2天前,但未能重新打开帖子:

原关闭原因未得到解决

如何通过其索引来删除数组的元素?

例如

fruits = ["mango","apple","pine","berry"];

删除元素fruits[2],得到

fruits = ["mango","apple","berry"];

admin 更改状态以发布 2023年5月21日
0
0 Comments

你可以使用splice方法,如下所示:array.splice(start_index, no_of_elements_to_remove)。以下是针对你示例的解决方案:

const fruits = ["mango","apple","pine","berry"]; 
const removed = fruits.splice(2, 1); // Mutates fruits and returns array of removed items
console.log('fruits', fruits); // ["mango","apple","berry"]
console.log('removed', removed); // ["pine"]

这将从索引2处移除一个元素,即在操作后fruits=["mango","apple","berry"];

0