2013-05-03 83 views
1

我正在從事Google Apps Script/JS中的項目,出於某種原因,當我嘗試使用對象複製對象數組時,出現意外的行爲。 create()方法。代碼的相關代碼片段如下,當函數完成時...原始數組對象被修改,即使第二個參數傳遞正確。數組/對象按值複製/按參考複製神祕

WebConfigParser.prototype.compareWith = function(array_of_objs, parameter_flag) 
    { 
    var safe_array_of_objs = []; 
    var array_of_objs_to_touch; 
    if(parameter_flag) 
    { 
    if(parameter_flag === "passbyval") 
    { 
     for(var i = 0; i < array_of_objs.length; i++) 
     { 
     safe_array_of_objs.push(Object.create(array_of_objs[i])); 
     } 
     array_of_objs_to_touch = safe_array_of_objs; 
    } 

    } 
    else 
    { 
    array_of_objs_to_touch = array_of_objs; 
    } 
    ///more code happens here...but i'm always referring to "array_of_objs_to_touch" 
} 

回答

0

爲了得到一維數組的深層副本,您可以使用Array.slice()

var a=[1,2,3], 
b=a.slice(), //deep copy 
c=a; 
a[1]=3; 
console.log(a,b,c)