arrays - 角度 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();
});
}
});
如果有人能对此有所了解,我将不胜感激。
解决方案
pet
提供给迭代器函数的是angular.forEach
对数组中对象的“引用”。调用pet = ...
是重新分配该引用以指向一个新对象,而不是更改原始对象。
pets[pkey] = ...
正在更新数组中的引用。
推荐阅读
- java - 在 sbt 中添加类路径位置
- rundeck - 安装 EC2-steps-plugin 时遇到问题
- javascript - 在 JSP 中看不到 Json 数据结果
- c++ - 从 .tsv 文件读入
- node.js - 从 Angular 和 Nodejs 请求 API 时出错
- python - 从python中的多行Excel工作表生成项目和子项目字段
- javascript - 为什么将 console.log() 放置在呈现视图的函数中时会重复打印一个变量?
- c# - 使用 JSON JavaScriptSerializer 在序列化或反序列化期间出现错误
- reactjs - React js CRUD - 添加数据时如何自动更新表而不刷新
- javascript - 在时间段之间获得整个三个月