创建函数将属性从一个对象复制到另一个对象
我正在尝试创建一个函数,该函数将从源对象复制所有属性并将它们粘贴到目标对象。我想创建一个深层副本,所以我没有使用 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)
- 使用该函数不会更改 obj2。我知道该函数使用引用传递,这就是为什么不重新分配对象的原因。有没有办法解决这个问题,以便编辑我作为参数传入的对象?
- obj1 中的reverseString 方法不会使用JSON.stringify 进行复制。这是为什么呢?
I am trying to create a function that will copy all properties from a source object and paste them to a destination object. I want to create a deep copy, so I am not using object.assign().
Here is my code:
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)
- obj2 is not changed using the function. I understand the function uses pass by reference, which is why the object is not reassigned. Is there a way around this so that the object I pass in as a parameter is edited?
- The reverseString method in obj1 does not get copied using JSON.stringify. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您要在函数内部设置对象或数组的值,则它是按值传递。因此,您需要通过引用传递对象或尝试此操作
或通过引用传递。在这种情况下,您仅更改对象内部的属性,而不是为整个对象分配新值
if you are setting the value of an object or array inside of function it is Pass by Value. So you need to pass object by reference or try this
or pass by reference. In this case you are only changing the property inside of the object, not assigning a new value to the whole object