gpt4 book ai didi

javascript - 在 Node.js 中克隆对象

转载 作者:IT老高 更新时间:2023-10-28 13:15:32 26 4
gpt4 key购买 nike

在 node.js 中克隆对象的最佳方法是什么

例如我想避免以下情况:

var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6

该对象很可能包含复杂类型作为属性,因此简单的 for(var x in obj1) 无法解决。我是否需要自己编写一个递归克隆,或者是否有一些我没有看到的内置内容?

最佳答案

可能性 1

简单的深拷贝:

var obj2 = JSON.parse(JSON.stringify(obj1));

可能性 2(已弃用)

注意:此解决方案现在在 documentation of Node.js 中被标记为已弃用。 :

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().

原答案::

对于浅拷贝,使用 Node 内置的 util._extend() 函数。

var extend = require('util')._extend;

var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5

Node的_extend函数源码在这里:https://github.com/joyent/node/blob/master/lib/util.js

exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin;

var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};

关于javascript - 在 Node.js 中克隆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055746/

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