Javascript 删除数组的第一项(如从堆栈中弹出)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29605929/
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-23 03:39:10  来源:igfitidea点击:

Remove first Item of the array (like popping from stack)

javascriptangularjs

提问by Raihan

I have list of items created via ng-repeat. I also have Delete button. Clicking delete button removes last item of the array one by one. Plunker

我有通过ng-repeat. 我也有删除按钮。点击删除按钮将数组的最后一项一项一项删除。普朗克

But I want to remove items one by one starting from the first item. How can I do that? I used this for removing list Items:

但我想从第一个项目开始一个一个地删除项目。我怎样才能做到这一点?我用它来删除列表项:

  $scope.index = 1;
  $scope.remove = function(item) { 
    var index = $scope.cards.indexOf(item);
    $scope.cards.splice(index, 1);     
  }

Is there any way I can remove from the top?

有什么办法可以从顶部删除吗?

回答by Thalsan

The easiest way is using shift(). If you have an array, the shiftfunction shifts everything to the left.

最简单的方法是使用shift(). 如果您有一个数组,该shift函数会将所有内容向左移动。

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

回答by Muhammad Danial Iqbal

Just use arr.slice(startingIndex, endingIndex).

只需使用arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

如果未指定endingIndex,则返回从提供的索引开始的所有项目。

In your case arr=arr.slice(1).

在你的情况下arr=arr.slice(1)

回答by Jo VdB

const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item

回答by Kushal

Plunker

普朗克

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

对 .. 进行了更改,现在它将从顶部移除

回答by Hazarapet Tunanyan

There is a function called shift(). It will remove the first element of your array.

有一个函数叫做shift(). 它将删除数组的第一个元素。

There is some good documentation and examples.

有一些很好的文档和示例