javascript - Problems with shallow copy in js.
世界只因有你
世界只因有你 2017-05-19 10:18:55
0
2
481

Looking at this piece of code today, talking about shallow copy

/* ================ 浅拷贝 ================ */
function simpleClone(initalObj) {
    var obj = {};
    for ( var i in initalObj) {
        obj[i] = initalObj[i];
    }
    return obj;
}

/* ================ 客户端调用 ================ */
var obj = {
    a: "hello",
    b: {
        a: "world",
        b: 21
    },
    c: ["Bob", "Tom", "Jenny"],
    d: function() {
        alert("hello world");
    }
}
var cloneObj = simpleClone(obj); // 对象拷贝

console.log(cloneObj.b); // {a: "world", b: 21}
console.log(cloneObj.c); // ["Bob", "Tom", "Jenny"]
console.log(cloneObj.d); // function() { alert("hello world"); }

// 修改拷贝后的对象
cloneObj.b.a = "changed";
cloneObj.c = [1, 2, 3];
cloneObj.d = function() { alert("changed"); };

console.log(obj.b); // {a: "changed", b: 21} // // 原对象所引用的对象被修改了

console.log(obj.c); // ["Bob", "Tom", "Jenny"] // 原对象所引用的对象未被修改
console.log(obj.d); // function() { alert("hello world"); } // 原对象所引用的函数未被修改

1. Logically speaking, shallow copy should not only copy the reference of the object, not the object itself, then both obj.c and obj.d should be modified?

2. var cloneObj=obj, does it count as a shallow copy? How to understand it?

世界只因有你
世界只因有你

reply all(2)
左手右手慢动作
var cloneObj=obj // 这才是浅拷贝,改变这里会联动改变
// 这个方法不是浅拷贝,是一级深拷贝,二级拷贝是浅拷贝,因为obj[i] = initalObj[i];就相当于你的var cloneObj=obj 。
function simpleClone(initalObj) {
    var obj = {};
    for ( var i in initalObj) {
        obj[i] = initalObj[i]; ////////注意这里  除非你递归赋值
    }
    return obj;
}

So

cloneObj.a = "changed"; // obj不变
cloneObj.b.a = "changed"; // obj改变
小葫芦
  1. The variable storing the object can be simply understood as an address, through which other child elements can be obtained. 2. Shallow copy of an object refers to creating a new object and copying the values ​​of its sub-elements in sequence. 3. Therefore, although the sub-element values ​​of the copied objects are the same, they are not equal when compared because the addresses where they store sub-element variables are different. 4. Your second method is direct assignment of addresses. No new variables are generated, or no new addresses for creating subelements are generated. This is not called copying.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template