angularjs forEach and splice

后端 未结 6 1191
梦如初夏
梦如初夏 2021-02-01 18:23

I have an array like this:

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


        
6条回答
  •  粉色の甜心
    2021-02-01 18:58

    The problem is that you remove elements from the array during the loop so later items are at different indices. You need to loop backwards instead:

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

    Here's an updated example.

提交回复
热议问题