Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a reference to a variable in javascript?

In the example below, it should print out false the first time, but it should be changed to true after that. But it stays the value it was originally assigned.

var i = {
  control: {
      a: false,
      b: false,
  }
}

var test = i.control['a'];

setInterval(function () {
  document.body.innerHTML += test + ', ';
  i.control['a'] = true;
}, 500);

I want to be able to update the variable externally, but the loop needs to be able to check what the variable is set to (which could be any of the values in that object, and will be set on initialization).

I am doing this to try to keep the code clean, and without having to create a new variable each loop to get/store the latest value.

like image 825
stackers Avatar asked Feb 14 '26 02:02

stackers


1 Answers

You could take the object reference and take the last key for the value.

var i = { control: { a: false, b: false } },
    test = i.control;

setInterval(function () {
    document.body.innerHTML += test.a + ', ';
    i.control.a = true;
}, 500);
like image 155
Nina Scholz Avatar answered Feb 15 '26 15:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!