在 for 循环中使用时拼接不起作用

jun*_*lik 1 javascript arrays multidimensional-array

我正在尝试从数组中删除一个项目,但它不起作用我正在使用以下代码

vm.Continue = function () {
    $scope.invalidList = [];
    if (vm.errorexsist === true) {
        var table = document.getElementById('errortabel');
        for (var r = 0, n = table.rows.length; r < n; r++) {
            if (r > 0) {
                $scope.invalidList.push({
                    Error: table.rows[r].cells[0].val   ,
                    FirstName: table.rows[r].cells[1].children[0].value,
                    Email: table.rows[r].cells[2].children[0].value,
                    PhoneNumber: table.rows[r].cells[3].children[0].value,
                    Location: table.rows[r].cells[4].children[0].value,
                    Department: table.rows[r].cells[5].children[0].value
                });
            }
        }
        var i = $scope.invalidList.length;
        while (i--) {
            if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {
                $scope.invalidList.splice(i, 1);
            }
        }  
    }
};
Run Code Online (Sandbox Code Playgroud)

上面的代码总是在 if else 条件不满足时删除零项。

Jor*_*ett 5

Array.splice 将修改数组的长度,因此您应该向后遍历数组,否则每次调用 splice 时,for 循环的索引和长度都会过时。

var i = $scope.invalidList.length
while (i--) {
    if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {   
        $scope.invalidList.splice(i, 1);   
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想根据条件从数组中删除项目,Array.filter则专为此目的而设计:

$scope.invalidList = $scope.invalidList.filter(item => !IsEmailValid(item.Email) || !IsPhoneNumValid(item.PhoneNumber))
Run Code Online (Sandbox Code Playgroud)