JSFiddle - React, Tailwind, and code Playground
JavaScript
function getType(variable){
type = typeof(variable);
if(type==="object"){
type = Object.prototype.toString.call(variable);
if(variable){
if(variable.length!==undefined && type!="[object Array]"){
return "array-like";
}
}
switch(type){
case "[object Null]": type="null"
break
case "[object Array]": type="array"
break
default: type="object"
break
}
}
return type;
}
function deepCopy(obj){
var copy;
if(obj instanceof Date){
return new Date(obj);
}
if(getType(obj)=="array"){
copy = [];
}
else if(getType(obj)=="object"){
copy = {};
}
else{
return obj;
}
if(obj===null){
return null;
}
for(var key in obj){
if(typeof obj[key] == "object"){
copy[key] = deepCopy(obj[key]);
}
else{
copy[key] = obj[key];
}
}
return copy;
}
var a = { x: 1, y: 2, z: [1, 2, 3], w: new Date(2014, 1, 1, 12, 0, 0) };
var b = deepCopy(a); // b — это отдельный объект
b.x = 10;
console.log(a.x); // 1
// a.z и b.z указывают на разные массивы:
b.z.push(4);
console.log(a.z); // [1, 2, 3]
// a.w и b.w независимы друг от друга
b.w.setFullYear(2015);
console.log(a.w.getFullYear()); // 2014
// Должно вернуть {a:1}, возвращает [a:1]
console.log(deepCopy({a:1}));
// Должно быть false
console.log('length' in deepCopy({}));