捕获变量的当前值

时间:2011-10-19 14:32:43

标签: javascript

我有一个不断变化的变量myVariable。在某些时候,我想将myVariable(不是引用myVariable)捕获到另一个变量myVariableAtSomePoint。< / p>

示例代码:

var myVariable = 1;

function test () {
    var myVariableAtSomePoint= myVariable;
    console.log(myVariableAtSomePoint);
}

myVariable = 2;

test(); // Prints 2, instead of 1.

4 个答案:

答案 0 :(得分:4)

您在评论中提到myVariable是一个数字。由于myVariable包含基本类型,因此只需使用以下代码:

myVariableAtSomePoint = myVariable;

看看JAVASCRIPT: PASSING BY VALUE OR BY REFERENCE。这是一个引用:

  

传入字符串或数字等基本类型变量时,   值按值传递。

我还建议阅读:How do I correctly clone a JavaScript object?

修改

我相信你假设函数在代码中的位置会影响变量的值。它不是。见下面的例子:

此:

function test () {
    var myVariableAtSomePoint= myVariable;
    console.log(myVariableAtSomePoint);
}

myVariable = 2;

test(); // Prints 2, instead of 1.

与此相同:

var myVariable = 1;

function test () {
    var myVariableAtSomePoint= myVariable;
    console.log(myVariableAtSomePoint);
}

myVariable = 2;

test(); // Prints 2, instead of 1.

您的问题是,您要将myVariable 的值更改为,并将其分配给myVariableAtSomePoint。为此,您可以根据需要调用test()函数之前更改myVariable的值

var myVariable = 1;

function test () {
    var myVariableAtSomePoint= myVariable;
    console.log(myVariableAtSomePoint);
}

test(); // Prints 1
myVariable = 2;
test(); // Prints 2

重要提示:无论函数的位置如何,在调用函数之前,test()内的代码都不会执行。

答案 1 :(得分:3)

变量只保存引用而不保留其他内容。如果需要变量指向的对象的副本,则需要某种方法来复制该对象。 您可以在对象本身上实现复制方法(如果您知道它具有哪些属性),或者您可以使用for ... in循环遍历对象上的所有属性并将它们复制到新分配的对象。 类似的东西:

//o is the object you want to copy
var o2 = {}; //gives a new object
for (x in o) {
   o2[x] = o[x];
}

答案 2 :(得分:1)

您的代码:

var myVariable = 1;

function test () {
    var myVariableAtSomePoint= myVariable;
    console.log(myVariableAtSomePoint);
}

myVariable = 2;

test(); // Prints 2, instead of 1.

您将2分配给myVariable,然后通过myVariablemyVariableAtSomePoint(现在值为2)分配给test(),当然它是2。

,这里需要任何魔术复制(因为数字是原始的)

答案 3 :(得分:0)

你只需要复制对象上的每个属性,当然如果有子对象,它们也可以通过引用传递:

function copy(o) { //could be called "clone"
  var i, n;
  n = {};
  for (i in o)
  {
    if (o.hasOwnProperty(i)) {
      n[i] = o[i];
    }
  }
  return n;
}