Remove first Item of the array (like popping from

2020-02-03 09:10发布

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

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?

5条回答
We Are One
2楼-- · 2020-02-03 09:24
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
查看更多
唯我独甜
3楼-- · 2020-02-03 09:27

Plunker

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

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

查看更多
家丑人穷心不美
4楼-- · 2020-02-03 09:29

Just use arr.slice(startingIndex, endingIndex).

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

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

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-02-03 09:42

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

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
查看更多
倾城 Initia
6楼-- · 2020-02-03 09:45

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

There is some good documentation and examples.

查看更多
登录 后发表回答