JS対象クローン方法のまとめ

3754 ワード

1.基本的な対象のclone
//   clone    ,      
var s = 'hello world';
var ss = s;
console.log(ss);
ss = "I'm changed";
console.log(s);
console.log(ss);
2.配列のclone
var a = [0,1,2,3];  
var b = a.slice(0);  
a = [3,2,1,0];  
console.log(a);
console.log(b);
3.対象のclone
let obj = {'a': 'a', 'b': 'b', 'c': 'c'};
let copy = Object.assign({}, obj);
console.log(copy);
4.すべての対象のclone
function clone(obj) {  
    var o;  
    if (typeof obj == "object") {  
        if (obj === null) {  
            o = null;  
        } else {  
            if (obj instanceof Array) {  
                o = [];  
                for (var i = 0, len = obj.length; i < len; i++) {  
                    o.push(clone(obj[i]));  
                }  
            } else {  
                o = {};  
                for (var j in obj) {  
                    o[j] = clone(obj[j]);  
                }  
            }  
        }  
    } else {  
        o = obj;  
    }  
    return o;  
}  

// test
var obj = {a: 'a', b: 'b', c: 'c'};
var copy = clone(obj);
参考文献:http://kingwell-leng.iteye.com/blog/1675694