首页 > 解决方案 > 角度 forEach 中的数组表示法

问题描述

我刚刚花了一个小时调试一个非常琐碎的问题。但我不明白为什么有时会在什么条件下发生这种行为。为了说明我的问题,让我们举一个例子。

$scope.vm.PetList = pets; // pets comes from resolved request
$scope.vm.Person = person; // person comes from resolved request

// init logic
if (angular.isDefined($scope.vm.Person.Pets) && $scope.vm.Person.Pets.length) {
    angular.forEach($scope.vm.Person.Pets, function (pet) {
        // this is the part that works sometimes
        pet = FunctionThatReturnsObjectOrNull($scope.vm.PetList, 'Id', pet.Id);
    });

    angular.forEach($scope.vm.Person.Pets, function (pet, pkey) {
        // this works every time
        $scope.vm.Person.Pets[pkey] = FunctionThatReturnsObjectOrNull($scope.vm.PetList, 'Id', pet.Id);
    });
}

我不知道为什么我想在这个特定的示例中从宠物集合中查找一个人的宠物,但它应该足以说明我遇到问题的地方。

重要的是要注意,作业的右侧总是正确评估。第一个示例中对变量的赋值pet并不总是代表数组的变化。

我理解为什么$scope.vm.Person.Pets[pkey]每次都工作,因为那是正确的数组表示法。但是该pet =符号可以省去跟踪keys嵌套数组的麻烦。

angular.forEach(collection, function (a) {
    if (a.collection.length > 0) {
        angular.forEach(a.collection, function (b) {
            b = doSomething();
        });
    }
});

如果有人能对此有所了解,我将不胜感激。

标签: arraysangularjs

解决方案


pet提供给迭代器函数的是angular.forEach对数组中对象的“引用”。调用pet = ...是重新分配该引用以指向一个新对象,而不是更改原始对象。 pets[pkey] = ...正在更新数组中的引用。


推荐阅读