How to remove element from an array in JavaScript?

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

var arr = [1,2,3,5,6];

I want to remove the 1st element of the array so that it becomes:

var arr = [2,3,5,6];

To extend this question, what if I want to remove the 2nd element of the array so that it becomes:

var arr = [1,3,5,6];

回答1:

For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:

var indexToRemove = 0; var numberToRemove = 1;  arr.splice(indexToRemove, numberToRemove);


回答2:

shift() is ideal for your situation. shift() removes the first element from an array and returns that element. This method changes the length of the array.

array = [1, 2, 3, 4, 5];  array.shift(); // 1  array // [2, 3, 4, 5]


回答3:

The Array.prototype.shift method removes the first element from an array, and returns it. It modifies the original array.

var a = [1,2,3] // [1,2,3] a.shift() // 1 a //[2,3]


回答4:

arr.slice(begin[,end])

is non destructive, splice and shift will modify your original array



回答5:

Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays.

Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method.

// Remove element at the given index Array.prototype.remove = function(index) {     this.splice(index, 1); }

So to remove the first item in your example, call arr.remove():

var arr = [1,2,3,5,6]; arr.remove(0);

To remove the second item,

arr.remove(1);

Here's a tiny article with insert and delete methods for Array class.

Essentially this is no different than the other answers using splice, but the name splice is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.



回答6:

Maybe something like this:

arr=arr.slice(1);


回答7:

If you want to remove one or many elements of an array depends on its content and/or its position.

You can use js filter array function.

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter.

Remove first element :

// Not very useful but it works function removeFirst(element, index) {   return index > 0; } var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]

Remove second element :

function removeSecond(element, index) {   return index != 1; } var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]

Remove odd element :

function removeOdd(element, index) {   return !(element % 2); } var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]


回答8:

Array.splice() has the interesting property that one cannot use it to remove the first element. So, we need to resort to

function removeAnElement( array, index ) {     index--;      if ( index === -1 ) {         return array.shift();     } else {         return array.splice( index, 1 );     } }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!