Home  >  Article  >  Web Front-end  >  Detailed explanation of js object deep cloning example

Detailed explanation of js object deep cloning example

小云云
小云云Original
2018-03-12 16:23:521594browse

Clone objects are often encountered during the development process. Sometimes shallow cloning is needed, and sometimes deep cloning is needed. This article mainly shares with you detailed examples of deep cloning of js objects. I hope it can help everyone.

// 深度克隆
function deepClone(origin, target) {
var target = target || {};
for (var prop in origin) {
if (origin.hasOwnProperty(prop)) {
if (origin[prop] !== null && typeof origin[prop] === 'object') {
target[prop] = Object.prototype.toString.call(origin[prop]) === '[object Array]'? [] : {};
deepClone(origin[prop], target[prop]);
} else {
target[prop] = origin[prop]
}
}
}
}
var obj = {
name: 'name',
arr: [1, 2, 3],
obj: { a: 'a' },
f: function () {
}
}
var obj1 = {};
deepClone(obj, obj1)
console.log(obj1)

Related recommendations:

One line of code to implement deep cloning of pure data json objects_javascript skills

The depth of JavaScript objects Introduction to cloning_javascript skills

Clone object method example tutorial

The above is the detailed content of Detailed explanation of js object deep cloning example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn