从数组中移除Item会在object的位置留下undefined

AngularJS Removing Item from Array Leaves undefined in place of object

本文关键字:位置 undefined object 会在 数组 Item      更新时间:2023-09-26

我一直在做一个AngularJS项目,以前遇到过这个问题。我的控制器中有如下数组:

$scope.items = [];

然后用调用REST API的对象填充这个数组:

$http.get(API_URL_HERE).then(onSuccess);

调用onSuccess方法,对象填充数组。我现在有:

console.log($scope.items)生成[Object, Object, Object, ...]

现在,当我在AngularJS ng-repeat循环中使用$scope.items时,它工作得很好,因为它应该但是,如果我试图从$scope.items数组中删除一个元素,它似乎总是删除元素,但将其替换为一个未定义的值,这个未定义的值由AngularJS在ng-repeat循环中解释,并在没有数据的模板中输出一个空行。例如,如果使用ng-show / ng-hide,即使数组中没有真正的对象,它仍然认为它是满的,因为它已经满了[undefined, undefined, undefined ...]

这引起了严重的头痛,我看到其他人有同样的问题,但修复似乎不太好。

我找到的解决方案,似乎工作得很好。还请注意,有些人说这只是一个纯Javascript的问题,好吧,我不认为它是,当我尝试在AngularJS和纯Javascript,我得到了2个不同的结果与相同的设置和数据。

例如,我有一个$scope.remove方法来处理从$scope.items数组中删除项目。

当我执行以下代码时:

$scope.items.splice(index, 1);

结果是console.log输出[Object, Object, undefined, Object, ...]

但是,通过执行以下代码:

$scope.items.splice(index, 1); $scope.items.pop();

从console.log [Object, Object, Object]和我的ng-repeat循环更新中得到以下输出,因为它应该没有空行。

我的解决方案似乎工作得很好,但请让我知道,如果你发现任何问题。这段代码显然比我在不同网站上看到的其他代码更干净,而且在我测试过的所有浏览器上都能正常工作。

更新

我的onSuccess方法是这样的:

var onSuccess = function(response){
    $scope.items = response.data.items;
    //results in [Object, Object, Object, ...]
};

我的$scope.remove方法是这样的:

$scope.remove = function(index){
    $scope.items.splice(index, 1);
    //results in [Object, Object, undefined, Object, ...]
    //add the following code
    $scope.items.pop();
    //results in [Object, Object, Object, ...] the undefined has gone
};

并且只有在添加pop方法时它才会正常工作