简体   繁体   English

如何在javascript中存储对变量的引用?

[英]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.在下面的例子中,它第一次应该打印出false,但之后应该改为true。 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.我这样做是为了保持代码干净,而不必在每个循环中创建一个新变量来获取/存储最新值。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM