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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2003815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:20:47  来源:igfitidea点击:

How to remove element from an array in JavaScript?

javascriptarrays

提问by user198729

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

Remove the first element

删除第一个元素

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

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

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

Remove the second element

删除第二个元素

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

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

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

回答by JP Silvashy

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.

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

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

array.shift(); // 1

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

回答by Gabriel McAdams

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

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

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

回答by p3drosola

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

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

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

回答by kiuma

arr.slice(begin[,end])

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

是非破坏性的,拼接和移位会修改你的原始数组

回答by Anurag

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

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

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.

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

// 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():

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

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

To remove the second item,

要删除第二项,

arr.remove(1);

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

这是一篇关于 Array 类的插入和删除方法的小文章

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

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

回答by ThatGuyYouKnow

Maybe something like this:

也许是这样的:

arr=arr.slice(1);

回答by Martin Choraine

Others answers are great, I just wanted to add an alternative solution with ES6Array function : filter.

其他答案很棒,我只是想添加一个带有ES6Array 函数的替代解决方案:filter

filter()creates a new array with elements that fall under a given criteria from an existing array.

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

So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.

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

Some examples :

一些例子 :

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]

Remove items not in stock

移除没有库存的物品

const inventory = [
  {name: 'Apple', qty: 2},
  {name: 'Banana', qty: 0},
  {name: 'Orange', qty: 5}
];

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


回答by Brendan

You can use the ES6 Destructuring Assignment feature with a rest operator. A comma indicates where you want to remove the element and the rest (...arr) operator to give you the remaining elements of the array.

您可以将 ES6 解构赋值功能与休息运算符一起使用。逗号表示要删除元素的位置,其余 (...arr) 运算符表示数组的剩余元素。

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]

回答by pie6k

Typescript solution that does not mutate original array

不改变原始数组的打字稿解决方案

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

回答by Keet Sugathadasa

There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).

有多种方法可以从数组中删除元素。让我指出下面最常用的选项。我写这个答案是因为我找不到从所有这些选项中使用什么的正确理由。问题的答案是选项 3 ( Splice())。

1) SHIFT() - Remove First Element from Original Array and Return the First Element

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

See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.

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

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() - Returns a Copy of the Array, Separated by a Begin Index and an End Index

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

See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.

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

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() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.

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

See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.

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

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"]