- 浅拷贝,如果对象的属性值是数或者字符串则值传递,否则为引用传递
function clone(obj){
return {...obj};
}
or
function clone(obj){
return Object.assign({},obj);
}
var t1 = {a: 'hello', b:[0, 1]}
var t2 = clone(t1);
t1.a = 'world';
console.log(t1.a, t2.a); // world hello
t1.b[0] = -1
console.log(t1.b[0], t2.b[0]); // -1 -1
- deepClone
function clone(obj) {
var newobj = obj.constructor === Array ? [] : {};
if (typeof obj !== "object") {
return obj;
} else {
for (var i in obj) {
newobj[i] = typeof obj[i] === "object" ? clone(obj[i]) : obj[i];
}
}
return newobj;
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj);
}
- Set 类型、Map 类型以及 Buffer 类型会被转换成 {}
- undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)
- 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误
- 结构化克隆,第一种推荐,参考JavaScript 深拷贝性能分析
function StructuredClone(param) {
return new Promise(function (res, rej) {
const {port1, port2} = new MessageChannel();
port2.onmessage = ev => res(ev.data);
port1.postMessage(param);
})
}
StructuredClone(objects).then(result => console.log(result))
function structuralClone(obj) {
const oldState = history.state;
history.replaceState(obj, document.title);
const copy = history.state;
history.replaceState(oldState, document.title);
return copy;
}
const clone = structuralClone(objects);
function structuralClone(obj) {
return new Notification('', {data: obj, silent: true}).data;
}
const obj = /* ... */;
const clone = structuralClone(obj);
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。