angularjs forEach和splice

时间:2014-06-13 10:15:33

标签: javascript angularjs array-splice

我有一个这样的数组:

$scope.emails = [
  {"key":"Work","value":"user@domine.com"},
  {"key":"","value":""},
   {"key":"Work","value":"user2@domine.com"}
  {"key":"","value":""}];

所以,我想删除空的电子邮件,但有角度forEach方法只删除一个最后一个对象的对象为什么???。

js代码

angular.forEach($scope.emails, function(email, index){
     if(email.value ===""){
       $scope.emails.splice(index, 1);

     } 

    });

我做错了

JS Bin

6 个答案:

答案 0 :(得分:53)

问题是您在循环期间从数组中删除元素,以便后面的项目处于不同的索引。你需要向后循环:

for (var i = $scope.emails.length - 1; i >= 0; i--) {
    if (!$scope.emails[i].value) {
        $scope.emails.splice(i, 1);
    }
}

这里是updated example

答案 1 :(得分:3)

像其他人指出的那样,代码的罪魁祸首是数组被删除了。要使用angular.forEach,您可以尝试添加/分配方法:

var filteredEmails = [];
angular.forEach($scope.emails, function(email, index){
    if(email.value !==""){
        filteredEmails.push(email);
    }
});

$scope.emails = filteredEmails;

答案 2 :(得分:2)

indexOf在找不到商品时会返回-1

删除项目并避免在找不到时删除最后一项的方法是:

var index = $scope.items.indexOf($scope.oldItem);

if (index != -1) {
  $scope.items.splice(index, 1);
}

答案 3 :(得分:1)

describe('Foreach Splice', function () {
  it('splicing', function () {

    var elements = [
      {name: "Kelly", age: 16},
      {name: "", age: 17},
      {name: "Becky", age: 18},
      {name: "", age: 18},
      {name: "Sarah", age: 19},
      {name: "", age: 20},
      {name: "", age: 22},
      {name: "Mareck", age: 21},
      {name: "", age: 21},
      {name: "Mareck", age: 21}
    ];

    removeEmptyEntry(elements);
    console.log(elements);
  });


  function removeEmptyEntry(elements) {
    elements.forEach(function (element, index) {
      if (!element.name) {
        elements.splice(index, 1);
        removeEmptyEntry(elements);
      }
    });
  }
});

答案 4 :(得分:0)

我还没有尝试使用AngularJs,但是使用Angular 4时,类似的方法效果非常好。

this.emailArray.forEach(email => {
  if (email.value == "") {
    this.emailArray.splice(this.emailArray.indexOf(email),1);
  }
});

Angular 4版本:

             <div class="dropdown">
                <span class="p-2 text-uppercase font-weight-semi-bold pointer dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    @topMenu.Name
                </span>
                <div class="dropdown-menu"  style="font-size:0.9rem" aria-labelledby="dropdownMenuButton">
                    @foreach (var subMenu in topMenu.SubMenu)
                    {
                        <a class="dropdown-item" href="@Url.Content("~/" + subMenu.Url)">@subMenu.Name</a>

                    }
                </div>
            </div>

答案 5 :(得分:-1)

根据docs,迭代器函数允许第三个参数,它是正在迭代的集合。拼接该集合而不是$scope.emails将删除预期的obejct。

angular.forEach($scope.emails, function(email, index, obj){
    if(email.value ===""){
        obj.splice(index, 1);
    } 
});