请参见下面的代码:
var fieldsControls = $filter('filter')(vm.FieldsControls, { FieldId: id });
for (var i = 0; i < fieldsControls.length; i++)
{
if (fieldsControls[i].ControlType == "DropDown") {
fieldsControls[i].Options = $filter('filter')(vm.Options, { type: fieldsControls[i].type });
}
}
return fieldsControls;
返回之后(甚至在for循环之后),我观察到原始数组“ vm.FieldsControls”正在使用新的Options值进行更新。但是,这不应该只更改新数组fieldControls吗?
最佳答案
首先准备阵列的深拷贝。这是代码:
var copy = angular.copy(vm.FieldsControls);
var fieldsControls = $filter('filter')(copy, { FieldId: id });
for (var i = 0; i < fieldsControls.length; i++)
{
if (fieldsControls[i].ControlType == "DropDown") {
fieldsControls[i].Options = $filter('filter')(vm.Options, { type: fieldsControls[i].type });
}
}
return fieldsControls;
关于javascript - 如何避免在使用$ filter后更新原始数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35343203/