如何从JavaScript中的数组中删除元素?

How to remove element from an array in JavaScript?

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

删除第一个元素

我想删除数组的第一个元素,使其变为:

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

删除第二个元素

扩展这个问题,如果我想删除数组的第二个元素以使其变为:

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


shift()非常适合您的情况。 shift()从数组中删除第一个元素并返回该元素。此方法更改数组的长度。

1
2
3
4
5
array = [1, 2, 3, 4, 5];

array.shift(); // 1

array // [2, 3, 4, 5]


要获得更灵活的解决方案,请使用splice()函数。它允许您根据索引值删除数组中的任何项目:

1
2
3
4
var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);


Array.prototype.shift方法从数组中删除第一个元素,然后返回它。它修改了原始数组。

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


1
arr.slice(begin[,end])

无损,拼接和移位会修改您的原始数组


写了一篇关于在Javascript数组中任意位置插入和删除元素的小文章。

这是从任何位置删除元素的小片段。这扩展了Javascript中的Array类,并添加了remove(index)方法。

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

因此,要删除示例中的第一项,请调用arr.remove():

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

要删除第二项,

1
arr.remove(1);

这是一篇带有Array类的insert和delete方法的小文章。

从本质上讲,这与使用splice的其他答案没有什么不同,但是名称splice是不直观的,并且如果在整个应用程序中都具有该调用,则只会使代码更难阅读。


也许是这样的:

1
arr=arr.slice(1);

其他答案很好,我只想添加ES6数组函数:filter的替代解决方案。

filter()创建一个新数组,其中的元素属于现有数组的给定条件。

因此,您可以轻松地使用它删除不符合条件的项目。此功能的好处是您可以在复杂的数组上使用它,而不仅仅是字符串和数字。

Some examples :

删除第一个元素:

1
2
3
4
5
// 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]

删除第二个元素:

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

删除奇数元素:

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

删除没有库存的物品

1
2
3
4
5
6
7
const inventory = [
  {name: 'Apple', qty: 2},
  {name: 'Banana', qty: 0},
  {name: 'Orange', qty: 5}
];

const res = inventory.find( product => product.qty > 0);

有多种方法可以从数组中删除元素。让我在下面指出最常用的选项。我之所以写此答案,是因为我无法从所有这些选项中找到合适的理由。该问题的答案是选项3(Splice())。

1)SHIFT()-从原始数组中删除第一个元素并返回第一个元素

请参见Array.prototype.shift()的参考。仅当您要删除第一个元素并且可以更改原始数组时,才使用此选项。

1
2
3
4
5
6
7
8
9
const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

2)SLICE()-返回数组的副本,由开始索引和结束索引分隔

请参见Array.prototype.slice()的参考。您不能从此选项中删除特定元素。您只能对现有阵列进行切片,并获得阵列的连续部分。就像从您指定的索引中剪切数组一样。原始阵列不受影响。

1
2
3
4
5
6
7
8
9
10
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel","duck","elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel","duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison","camel","duck","elephant"]

3)SPLICE()-通过删除或替换特定索引处的元素来更改数组的内容。

请参见Array.prototype.splice()的参考。 splice()方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。返回更新的数组。原始数组得到更新。

1
2
3
4
5
6
7
8
9
10
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan","Feb","March","April","June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan","Feb","March","April","May"]

您可以将ES6解构分配功能与rest运算符一起使用。逗号指示要删除元素的位置以及其余(... arr)运算符,以为您提供数组的其余元素。

1
2
3
4
5
6
7
8
9
const source = [1,2,3,5,6];

function removeFirst(list) {
   var  [, ...arr] = list;
   return arr;
}
const arr = removeFirst(source);
console.log(arr); // [2, 3, 5, 6]
console.log(source); // [1, 2, 3, 5, 6]


不改变原始数组的Typescript解决方案

1
2
3
function removeElementAtIndex< T >(input: T[], index: number) {
  return input.slice(0, index).concat(input.slice(index + 1));
}

Array.splice()具有一个有趣的属性,即不能使用它删除第一个元素。因此,我们需要诉诸

1
2
3
4
5
6
7
8
9
function removeAnElement( array, index ) {
    index--;

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


您也可以使用reduce来做到这一点:

1
2
3
4
5
6
7
8
9
10
11
12
let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())