是否有任何键值结构是可变的JavaScript?


const cache = {};
//adding key-value pair
cache.John = {lastName:"foo"}

//assigning John to a new variable
const John = cache.John;

//changing the cache object
cache.John.lastName = "bar";

console.log(John); // { lastName: 'bar'}

上面的代码表明,即使对象值被保存到一个变量中,然后进行了更改,该变量的值也会发生变化。

对于我的代码,我需要使用一个更好的结构,如Map,然而,当Map值被改变时,引用保持设置为旧值。

const cache = new Map();
cache.set("John",{lastName:"foo"});

const John = cache.get("John");
cache.set("John",{lastName:"bar"});
console.log(John); // { lastName: 'foo'}

是否有办法也"update"参考使用Map?JavaScript中还有其他可变结构吗?

Map示例不能工作的原因是您在检索原始对象后使用新对象对其进行了设置。相反,您可以简单地从另一个引用实例中修改对象,您将看到所有引用中的更改。

对于更复杂的交互,您可以查看Proxy

const cache = new Map();
cache.set("John",{lastName:"foo"});

const John = cache.get("John");
const temp = cache.get("John");
temp.lastName = 'bar';

console.log(John); // { lastName: 'bar'}

就用…复制对象的内容,如:

const cache = {};
//adding key-value pair
cache.John = {lastName:"foo"}

//assigning John to a new variable
const John = {...cache.John};

//changing the cache object
cache.John.lastName = "bar";

console.log(John); // { lastName: 'bar'}

相关内容

最新更新