javascript – Angular.copy()不会复制所有属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – Angular.copy()不会复制所有属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2667字,纯文字阅读大概需要4分钟。
内容图文
![javascript – Angular.copy()不会复制所有属性](/upload/InfoBanner/zyjiaocheng/819/1047fc79e4714419826fa9e558de8a47.jpg)
考虑服务中的以下功能:
$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()不会复制所有属性全部内容,希望文章能够帮你解决javascript – Angular.copy()不会复制所有属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。