2016-10-24 41 views
2

我如何使playerinitemptyseats刪除所用的座位? 可以說seatid是1,那麼它會從emptyseats刪除seat: 1Angularjs的方式從陣列中刪除項目

vm.emptyseats = [ 
     {seat: 1}, 
     {seat: 2}, 
     {seat: 3}, 
     {seat: 4}, 
     {seat: 5}, 
     {seat: 6}, 
     {seat: 7}, 
     {seat: 8}, 
     {seat: 9}, 
    ]; 


    vm.playerinit = function(x) { 
     console.log("init user data"); 
     var seatid = x.position; 

     // vm.emptyseats remove where seat: seatid 

    }; 
+1

可能重複[按值刪除項目](http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value) –

回答

2

使用本機Array#filter功能:

vm.playerinit = function(x) { 
     console.log("init user data"); 
     var seatid = x.position; 

     // vm.emptyseats remove where seat: seatid 
     //Using ES6 arrow function syntax 
     vm.emptyseats = vm.emptyseats.filter((empty_seat) => empty_seat.seat !== seatid); 
     //Or regular syntax 
     vm.emptyseats = vm.emptyseats.filter(function(empty_seat) {  return empty_seat.seat !== seatid}); 

    }; 
+0

應該注意的是['Array.filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#AutoCompatibilityTable)是IE9 +。儘管如此,還是一個很好的答案 – Sam

+0

謝謝,我編輯了我的答案。 –

+0

謝謝@GonzaloPincheiraArancibia! 。我會盡快接受它。 – maria

1

首先,您需要找到要刪除的數組的索引。然後,使用Array.splice()

var seatid = x.position; 
angular.forEach(vm.emptyseats, function(emptyseat, i) { 
    if(emptyseat.seat !== seatid) return; 
    vm.emptyseats.splice(i, 1); 
}); 
+2

據我所知,'' forEach'在IE8上也不支持。 – Mistalis

+0

Duh,謝謝@Mistalis。我想我已經習慣了那個人。我已經更新使用Angular的'forEach()'。 – Sam

-2

使用.splice()嘗試這樣做。 vm.emptyseats.splice(0,1);

0

你可以用一個簡單的循環for刪除它:

for(var i = 0; i < emptyseats.length; i++) { 
    if(vm.emptyseats[i].seat == seatid) vm.emptyseats.splice(i, 1); 
} 

隨着您的全碼:

vm.playerinit = function(x) { 
    console.log("init user data"); 
    var seatid = x.position; 

    // vm.emptyseats remove where seat: seatid 
    for(var i = 0; i < emptyseats.length; i++) { 
     if(vm.emptyseats[i].seat == seatid) { 
      vm.emptyseats.splice(i, 1); 
      console.log(seatid + " removed!"); 
     } 
    } 
}; 
1

一個土生土長的JS方法,IE 9

vm.emptyseats = vm.emptyseats.filter(function(a) { return a.seat != seatid; }); 

Array.prototype.filter()