代码之家  ›  专栏  ›  技术社区  ›  iiminov

角forEach中的数组表示法

  •  0
  • iiminov  · 技术社区  · 7 年前

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

    $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();
            });
        }
    });
    

    如果有人能解释这一点,我将感谢他们的努力。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andy Lamb    7 年前

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