克隆Node.js中的对象 [英] Cloning an Object in Node.js
问题描述
在node.js中克隆对象的最佳方法是什么
What is the best way to clone an object in node.js
例如。我想避免以下情况:
e.g. I want to avoid the situation where:
var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6
对象可能包含复杂类型作为属性,因此很简单(var x在obj1)不会解决。我是否需要自己编写一个递归克隆,或者是否有内置的东西我没有看到?
The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?
推荐答案
可能性1
低档深拷贝:
Possibility 1
Low-frills deep copy:
var obj2 = JSON.parse(JSON.stringify(obj1));
可能性2(已弃用)
注意:此解决方案现已在 Node.js <的文档中标记为已弃用/ a>:
Possibility 2 (deprecated)
Attention: This solution is now marked as deprecated in the documentation of Node.js:
util._extend()方法从不打算在内部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.
它已被弃用,不应在新代码中使用。 JavaScript通过Object.assign()提供非常相似的内置功能。</ p>
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()
函数。
For a shallow copy, use Node's built-in util._extend()
function.
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
Source code of Node's _extend
function is in here: 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;
};
这篇关于克隆Node.js中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!