[英]How to remove an element from array in javascript without making a new?
I read many answers but I didn't understand how to use splice in this case.. Suppose i have an array named alphabets like - ["a","b","c","d","e"] and i have to remove c from it.我阅读了很多答案,但我不明白在这种情况下如何使用 splice .. 假设我有一个名为字母的数组,如 - ["a","b","c","d","e"] 和我必须从中删除 c 。 I dont want to create another array with c removed instead i want to update the same list each time an item is removed just like remove method in python.
我不想创建另一个删除 c 的数组,而是我想在每次删除项目时更新相同的列表,就像 python 中的 remove 方法一样。 I know the index also so it can be like alphabets.remove[3]...to remove c.
我也知道索引,所以它可以像字母表.remove[3]...删除c。 Please help me i am beginner.
请帮助我,我是初学者。
Actually it would be better if there's a way that i can remove using just index number cause the names in array are very tough.实际上,如果有一种方法可以仅使用索引号来删除它会更好,因为数组中的名称非常困难。 Any help is appreciated
任何帮助表示赞赏
To modify the array rather than creating a new one, as you said you'd want the splice
method .要修改数组而不是创建一个新数组,正如您所说,您需要
splice
方法。 You pass the index of the item to remove, and the number of items to remove at that index:您传递要删除的项目的索引,以及要在该索引处删除的项目数:
const index = theArray.indexOf("c");
theArray.splice(index, 1);
Live Example:现场示例:
const theArray = ["a","b","c","d","e"]; const rememberArray = theArray; // Just so we can prove it's the same array later const index = theArray.indexOf("c"); theArray.splice(index, 1); console.log(theArray); console.log("Same array? " + (rememberArray === theArray));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.