gpt4 book ai didi

javascript - Angular.copy() 不会复制所有属性

转载 作者:搜寻专家 更新时间:2023-11-01 05:21:55 24 4
gpt4 key购买 nike

考虑服务中的以下功能:

$scope.addPeriod = function(newPeriod) {        
if(newPeriod.from !== '' && newPeriod.until !== '') {
var index = $scope.newPeriods.indexOf(newPeriod);
$scope.newPeriods.splice(index, 1);
$scope.setHolidayEditions(newPeriod);


console.log("Check period");
console.log(newPeriod); // state 1: object newPeriod is as expected, it contains holidayEdtions

console.log("Check period copy");
console.log(angular.copy(newPeriod)); //state 2 : object newPeriod is missing the holidayeditions!
$scope.periods.push(angular.copy(newPeriod)); //original code
//some more logic irrelevant to the question
}
}

问题出在 angular.copy() 中。 newPeriod对象的结构如下:

它有一个“开始”日期和一个“结束”日期以及一组杂志对象。然后是函数$scope.setHolidayEditions(newPeriod)。基本上,它向每本杂志添加了一系列版本对象。这个功能有效。我知道这是因为控制台输出。在原始代码中,句点随后开始推送到句点数组中,然后显示在屏幕上。完成 angular.copy() 可能是为了避免引用问题。

但是 angular.copy() 似乎并没有复制杂志对象中新制作的版本数组。是否有一个原因?

基本上这是服务函数中发生的事情:

我有一个名为 newPeriod 的对象,它看起来像这样:

{
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode"},
{title:"other title", number:"other number", code:"magazineCode2"}
]
}

在函数 $scope.setHolidayEditions(newPeriod) 之后对象看起来像这样:

    {
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode", holidayEditions:["date","date","date"]},
{title:"other title", number:"other number", code:"magazineCode2", holidayEditions:["date","date","date"]}
]
}

但是在 angular.copy(newPeriod) 之后,对象又变成了这个样子:

 {
from:"02/10/2015",
until:"09/10/2015",
magazines: [
{title:"some title", number:"some number", code:"magazineCode"},
{title:"other title", number:"other number", code:"magazineCode2"}
]
}

angular.copy() 没有复制杂志的 holidayEditions 数组。我想知道为什么?

最佳答案

你是对的,我前段时间遇到了同样的问题。因此(也出于其他一些原因)我决定使用 lodash它为那个问题提供了一个功能:

_.cloneDeep(value, [customizer], [thisArg])

Creates a deep clone of value. If customizer is provided it’s invoked to produce the cloned values. If customizer returns undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up to three argument; (value [, index|key, object]).

Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments objects and objects created by constructors other than Object are cloned to plain Object objects. An empty object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.

关于javascript - Angular.copy() 不会复制所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32907525/

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