2

我正在使用 Google Apps Script/JS 开发一个项目,由于某种原因,当我尝试使用 Object.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"
}
4

1 回答 1

0

要获得一维数组的深层副本,您可以使用Array.slice()

var a=[1,2,3],
b=a.slice(), //deep copy
c=a;
a[1]=3;
console.log(a,b,c)
于 2013-05-03T17:27:08.467 回答