gpt4 book ai didi

javascript - 如何避免在使用 $filter 后更新原始数组?

转载 作者:行者123 更新时间:2023-11-30 16:17:02 25 4
gpt4 key购买 nike

请看下面的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com