简体   繁体   English

Javascript对变量的不安全引用

[英]Javascript unsafe references to variable

The code below doesn't work the way I want.下面的代码不能按我想要的方式工作。 I think the problem is probably related to unsafe reference.我认为问题可能与不安全的引用有关。

 var values = { "key1": "val1", "key2": "val2" }; const properties = {}; for (key in values) { properties[key] = { get: () => values[key], set: (val) => { values[key] = val } }; } console.log(properties["key1"].get()); // Result should be val1 but it prints val2

How can I run the above code as I want?如何根据需要运行上述代码?

 var values = { "key1": "val1", "key2": "val2" }; const properties = {}; for (const key in values) { properties[key] = { get: () => values[key], set: (val) => { values[key] = val } }; } console.log(properties["key1"].get());

as per Jaromanda X told in the comment, the variable key is initiating as the global variable, and the global variable holds the last entry of the object, so try by making the key as a variable of for loop so, for each iterate of for loop it holds the value of key as a local variable, please check the above snippet按照 Jaromanda X 在评论中的说法,变量key作为全局变量启动,全局变量保存对象的最后一个条目,因此尝试将key作为 for 循环的变量,因此,对于 for 的每次迭代循环它保存key的值作为局部变量,请检查上面的代码片段

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

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