Qwe Qwe
Qwe Qwe

Reputation: 495

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?

Upvotes: 1

Views: 264

Answers (1)

CodeBug
CodeBug

Reputation: 1667

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

Upvotes: 1

Related Questions