克隆JavaScript对象的最有效方法是什么?我已经看到obj = eval(uneval(o));
被使用,但这是非标准的,只有Firefox支持.
我做过类似的事情,obj = JSON.parse(JSON.stringify(o));
但质疑效率.
我也看到了具有各种缺陷的递归复制功能.
我很惊讶没有规范的解决方案.
我有一个超类是父(Entity
)对于很多子类(Customer
,Product
,ProductCategory
...)
我正在寻找动态克隆在Typescript中包含不同子对象的对象.
例如:a Customer
有不同的Product
人有ProductCategory
var cust:Customer = new Customer ();
cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));
Run Code Online (Sandbox Code Playgroud)
为了克隆整个对象树,我创建了一个函数 Entity
public clone():any {
var cloneObj = new this.constructor();
for (var attribut in this) {
if(typeof this[attribut] === "object"){
cloneObj[attribut] = this.clone();
} else {
cloneObj[attribut] = this[attribut];
}
}
return cloneObj;
}
Run Code Online (Sandbox Code Playgroud)
在new
上升时,它被transpiled为JavaScript以下错误:error TS2351: Cannot use 'new' with an expression whose type lacks a call or …
我有一个输入的对象数组.让我们来称呼它content
.
尝试深度复制时,它仍然具有对前一个数组的引用.
我需要复制该输入数组,并更改重复部分的一个属性.
很久以来我尝试了不成功的不同方法.
ES6方式:
public duplicateArray() {
arr = [...this.content]
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}
Run Code Online (Sandbox Code Playgroud)
该slice
方式:
public duplicateArray() {
arr = this.content.slice(0);
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}
Run Code Online (Sandbox Code Playgroud)
在这两个数组中,所有对象都有status: 'Default'
.
在Angular 2中深度复制数组的最佳方法是什么?
请帮助我使用角度2将对象复制到另一个对象?
在角度我使用angular.copy()将对象复制到旧对象的松散引用.但是,当我使用相同的角度2得到以下错误:
错误:未定义角度.
我正在开发一个将Angular和Underscore都作为依赖项的项目.
当我需要创建一个对象的副本时,根据我当时的心情,我可能会使用angular.copy()
或_.clone()
在我看来,这些方法中的一种可能比另一种方法更快/更可靠/更健壮.
假设两个库都已包含在内,那么这些函数中的任何一个是否存在任何已知问题,使其使用比其他函数更好或更差?
我正在使用TypeScript处理Angular 2.我有用户管理组件,我有整个用户的表.
当单击表中的任何用户时,然后形成具有要编辑的整个属性的外观.选择用户发生事件如下:
onUserSelected(event) {
var selectedId = event.data.id;
this.selectedUser = this.users.filter(user => user.id === selectedId)[0]
}
Run Code Online (Sandbox Code Playgroud)
问题是当正在编辑selectedUser时,他的属性也会在表中发生变化而且看起来不太好.我尝试自己创建副本如下,但它没有帮助 - 用户类
clone() {
var cloned = new User(this.id, this.login, this.name, this.surname, this.phone);
return cloned;
}
Run Code Online (Sandbox Code Playgroud)
也许我正在做一些在Angular2中不好的做法?