![](/img/trans.png)
[英]How to copy properties from one object to another in typescript
[英]Create Function to Copy Properties From One Object to Another
我正在尝试创建一个 function,它将从源 object 复制所有属性并将它们粘贴到目标 object。我想创建一个深拷贝,所以我没有使用 object.assign()。
这是我的代码:
var obj1 = {
arr: ['a','b','c','d'], // >= 4 elements, all should be truthy
obj: {a:1,b:2,c:3,d:4}, // >= 4 values, all should be truthy
halfTruthyArr: [null,'b',null,'d'], // >= 4 elements, half should be falsy
halfTruthyObj: {a:1,b:null,c:3,d:null}, // >= 4 values, half should be falsy
string: 'This is a string.',
reverseString: function (string) {
if (typeof string === 'string') return string.split('').reverse().join('');
}
};
var obj2 = {}
function extend(destination, source) {
destination = JSON.parse(JSON.stringify(source))
}
extend(obj2,obj1)
console.log(obj2)
如果您正在设置 object 或 function 内部数组的值,则它是按值传递。 所以你需要通过引用传递 object 或者试试这个
function extend(source) {
return JSON.parse(JSON.stringify(source))
}
var obj2=extend(obj1);
console.log("ext",obj2)
或通过引用传递。 在这种情况下,您只是更改 object 内部的属性,而不是为整个 object 分配新值
function extend(source, destination) {
destination.result = JSON.parse(JSON.stringify(source));
}
var destination = { result: {} };
extend(obj1, destination);
var obj2=destination.result;
console.log("ext", obj2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.