可能重複:
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