gpt4 book ai didi

javascript - angular.copy 不复制具有子对象或数组的对象

转载 作者:行者123 更新时间:2023-12-03 01:25:30 24 4
gpt4 key购买 nike

我正在使用 angularjs 1.5,并尝试将一个对象复制到另一个变量中。为了复制变量,我使用 angular.copy() function 。目标变量未获取源中的所有值。

Below is my code

$scope.searchCond = {
group_id:[],
sections:[]
};
for(var i=1;i<5;i++) {
$scope.searchCond.sections[i+"_sec"]=[];
$scope.searchCond.sections[i+"_sec"]["section_id"]=[];
$scope.searchCond.sections[i+"_sec"]["section_id"].push(i);
};
var tmpVar = angular.copy($scope.searchCond);
console.log(tmpVar);
console.log($scope.searchCond);

Output of both the console are given below

$scope.searchCond 的输出

{group_id: Array(0), sections: Array(0)}
group_id:[]
sections:Array(0)
1_sec:[section_id: Array(1)]
2_sec:[section_id: Array(1)]
3_sec:[section_id: Array(1)]
4_sec:[section_id: Array(1)]

tmpVar 的输出

{group_id: Array(0), sections: Array(0)}
group_id:[]
sections:Array(0)
length:0

tmpVar 未从源对象 $scope.searchCond 复制部分(1_sec,2_sec)

这个问题有解决办法吗?

最佳答案

$scope.searchCond = {
group_id:[],
̶s̶e̶c̶t̶i̶o̶n̶s̶:̶[̶]̶
sections:{}
};
for(var i=1;i<5;i++) {
̶$̶s̶c̶o̶p̶e̶.̶s̶e̶a̶r̶c̶h̶C̶o̶n̶d̶.̶s̶e̶c̶t̶i̶o̶n̶s̶[̶i̶+̶"̶_̶s̶e̶c̶"̶]̶=̶[̶]̶;̶
$scope.searchCond.sections[i+"_sec"]={};
$scope.searchCond.sections[i+"_sec"]["section_id"]=[];
$scope.searchCond.sections[i+"_sec"]["section_id"].push(i);
};
var tmpVar = angular.copy($scope.searchCond);
console.log(tmpVar);
console.log($scope.searchCond);

angular.copy函数仅复制数组的数字属性。如果您希望属性名称为非数字,请将其初始化为对象。

关于javascript - angular.copy 不复制具有子对象或数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51568812/

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