首页 文章资讯内容详情

如何克隆除JavaScript中的一键以外的js对象?

2026-06-04 1 花语

除一个键外,克隆对象的最简单方法是克隆整个对象,然后删除不需要的属性。克隆可以是2种类型-

深克隆

浅克隆

浅拷贝应尽可能少地重复。集合的浅表副本是集合结构的副本,而不是元素。对于浅表副本,现在两个集合共享各个元素。

示例

let innerObj = { a: b, c: d } let obj = { x: "test", y: innerObj } // Create a shallow copy. let copyObj = Object.assign({}, obj); // Both copyObj and objs prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj) This will give the output: { x: test, y: { a: test, c: d } } { x: test, y: { a: test, c: d } }

请注意,浅表副本不会递归创建克隆。它只是在顶层执行。

深层副本会复制所有内容。集合的深层副本是两个集合,其中原始集合中的所有元素都被克隆。

示例

let innerObj = { a: b, c: d } let obj = { x: "test", y: innerObj } // Create a deep copy. let copyObj = JSON.parse(JSON.stringify(obj)) // Both copyObj and objs prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj) This will give the output: { x: test, y: { a: test, c: d } } { x: test, y: { a: b, c: d } }

使用上述两种方法之一获得副本后,都可以使用delete关键字删除不需要的属性。例如,

示例

let original = { x: test, y: { a: test, c: d } } let copy = JSON.parse(JSON.stringify(original)) delete copy[x] console.log(copy) console.log(original) This will give the output: { y: { a: test, c: d } } { x: test, y: { a: test, c: d } }