如何在不指向同一对象的情况下复制变量?

时间:2012-05-29 15:10:44

标签: javascript object

  

可能重复:
  What is the most efficient way to clone a JavaScript object?(其中大多数使用外部库,或者不完全正常工作。下面的博客文章是一个更好的资源)

这是在scribd开发者挑战的背景下。他们的API允许我调用get_board并获得董事会。但是,我想要做的是拥有我在set_field中修改的那块板的副本。但是,当我这样做时,它会混淆自己的内部板对象并破坏他们的代码。所以,我需要(我认为)是调用get_board然后打破指向该对象的指针并拥有我自己修改的板。我在下面用mygame.board尝试了这个,但我仍然得到同样的错误。

错误内容为:The type of an object is incompatible with the expected type of the parameter associated to the object

function new_game()
{
    var board = get_board();
    var mygame={board: board}
    mygame.board = set_field(min_max_store, mygame.board)
}

function set_field(min_max_store, board)
{

  //loop x
   //loop y
    board[x][y] = -1;
return board
}

如何阻止指针指向其对象并自行修改?

编辑:

这适用于2D阵列。

var one = [[1,2],[2,3],[3,4],[4,5]]
var two = one.slice(0)

for(var x = 0; x <= one.length - 1; x++)
{
  two[x] = one[x].slice(0)
}

one[1][1] = 10

console.log(one)
console.log(two)

返回:

[[1, 2], [2, 10], [3, 4], [4, 5]]
[[1, 2], [2, 3], [3, 4], [4, 5]]

1 个答案:

答案 0 :(得分:3)

当您复制对象时,它将始终创建一个指针。但对于原始类型而言,情况并非如此。

您可以使用循环遍历对象的方法并递归地获取所有参数(深度)。另一种方法(草率,但它会起作用)是将对象编码为JSON,然后将其解码回新变量。

示例:

var foo = 5;
// This is not a pointer, since it is a primitive type
var bar = foo;
// 'foo' will stay at 5
bar = 537;

var object_one = {
  var1: 3,
  var2: 5,
};

// This is just a pointer.
var object_two = object_one;

// This will change 'var1' of 'object_one' as well as 'object_two'
object_two.var1 = 5;

使用JSON的示例:

var object_one = {
  var1: 'bar',
  var2: 5,
};
// A quick but dirty way to make a clone of the object without using a pointer 
var object_two = JSON.parse(JSON.stringify(object_one));

使用递归的示例:

function clone_object(p_obj) {
  var new_obj = new Object;
  if (typeof(p_obj) == 'object') {
    for (var i in p_obj) {
      new_obj[i] = clone_object(p_obj[i]);
    }
    return new_obj;
  } else {
    return p_obj;
  }
}

var object_one = {
  var1: 'bar',
  var2: 5,
};
var object_two = clone_object(object_one); 

http://james.padolsey.com/javascript/deep-copying-of-objects-and-arrays/