Angularjs从数组中删除项目的方法

时间:2016-10-24 14:45:04

标签: javascript angularjs arrays

如何让playerinit删除emptyseats使用的座位? 假设seatid为1,那么它会从seat: 1删除emptyseats吗?

   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

    };

5 个答案:

答案 0 :(得分: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});

    };

答案 1 :(得分: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 :(得分:1)

本机JS方法,IE 9 +

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

Array.prototype.filter()

答案 3 :(得分: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!");
      }
  }
};

答案 4 :(得分:-2)

尝试使用.splice()执行此操作。 vm.emptyseats.splice(0,1);