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

删除第一个元素

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

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

删除第二个元素

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

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

当前回答

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

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

请参阅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() -返回数组的副本,由开始索引和结束索引分开

参见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() -通过删除或替换特定索引上的元素来改变数组的内容。

请参阅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"]

其他回答

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

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

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

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

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

要去掉第二项,

arr.remove(1);

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

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

对于更灵活的解决方案,使用splice()函数。它允许你根据索引值删除数组中的任何项:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

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

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

你可以使用rest操作符来使用ES6解构赋值功能。逗号表示要删除元素的位置,rest(…arr)操作符表示数组的剩余元素。

Const source = [1,2,3,5,6]; 函数removeFirst(list) { Var[,…]Arr] =列表; 返回arr; } const arr = removeFirst(源); console.log (arr);// [2,3,5,6] console.log(源);// [1,2,3,5,6]

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

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

array.shift(); // 1

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