可能重复:
What is the most efficient way to clone a JavaScript object?如何克隆js对象?
如何克隆JS有了这样出来的参考对象:
{ ID: _docEl,
Index: next,
DocName: _el
}
任何想法?
可能重复:
What is the most efficient way to clone a JavaScript object?如何克隆js对象?
如何克隆JS有了这样出来的参考对象:
{ ID: _docEl,
Index: next,
DocName: _el
}
任何想法?
您必须遍历该对象并复制其所有属性。
然后,如果它的任何属性也是对象,假设你想克隆它们,你将不得不缓存到它们中。
有在这里做这个的各种方法: What is the most efficient way to clone a JavaScript object?
function objToClone(obj){
return (new Function("return " + obj))
}
EW,的eval()!不知道这也可以,除非obj有一个有意义的toString()方法。 – thomasrutter 2010-08-13 07:22:39
会不会返回一个引用? – borrel 2013-07-31 13:21:55
这是我怎么会做它的基础上,thomasrutter's suggestion(未测试的代码):
function cloneObj(obj) {
var clone = {};
for (var i in obj) {
if (obj[i] && typeof obj[i] == 'object') {
clone[i] = cloneObj(obj[i]);
} else {
clone[i] = obj[i];
}
}
return clone;
}
JavaScript的JS对象克隆
Object._clone = function(obj) {
var clone, property, value;
if (!obj || typeof obj !== 'object') {
return obj;
}
clone = typeof obj.pop === 'function' ? [] : {};
clone.__proto__ = obj.__proto__;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
value = obj.property;
if (value && typeof value === 'object') {
clone[property] = Object._clone(value);
} else {
clone[property] = obj[property];
}
}
}
return clone;
};
CoffeeScript JS对象克隆
# Object clone
Object._clone = (obj) ->
return obj if not obj or typeof(obj) isnt 'object'
clone = if typeof(obj.pop) is 'function' then [] else {}
# deprecated, but need for instanceof method
clone.__proto__ = obj.__proto__
for property of obj
if obj.hasOwnProperty property
# clone properties
value = obj.property
if value and typeof(value) is 'object'
clone[property] = Object._clone(value)
else
clone[property] = obj[property]
clone
现在你可以尝试这样做,
A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true
您可以使用jQuery.extend:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
下面的文章是如此的帮助:
What is the most efficient way to deep clone an object in JavaScript?
还要注意,这不是一刀切的 - 这不太可能对内置对象(如您希望使用cloneNode()方法等的DOM节点)有用。 – thomasrutter 2010-08-13 07:35:51