Published
Edited
Apr 8, 2020
Insert cell
md`# Javascript 值拷贝`
Insert cell
function deepCopy(obj){
// object
if(typeof obj === 'object'){
// 排除null;
if(obj === null){
return null;
}
// array
if(Array.isArray(obj)){
const newArr = [];
for(let i=0;i<obj.length;i++){
const item = deepCopy(obj[i]);
newArr.push(item);
}
return newArr;
}
// other->object
const keys = Object.keys(obj);
const tempObj = {};
for(let key of keys){
const v = obj[key];
tempObj[key] = deepCopy(v);
}
return tempObj;
}else{
return obj;
}
};
Insert cell
mock = ({
a:'111',
b:[1,2,3,4,5,{
s:null,
ss:undefined,
sss:[111]
}],
c:{
cc:{
ccc:'2222'
},
ccc02:[555],
},
f:()=>{
console.log('function value');
}
});
Insert cell
r = deepCopy(mock);
Insert cell
r.b.s = 'new s value'; // r.b.s =>'new s value'; mock.b.s => null
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more