JavaScript sets and value objects [duplicate]

会有一股神秘感。 提交于 2020-01-05 11:25:08

问题


I want to create a set of value objects in JavaScript. The problem is that in JavaScript equality is based on identity. Hence, two different objects with the same value will be treated as unequal:

var objects = new Set;

objects.add({ a: 1 });
objects.add({ a: 1 });

alert(objects.size);   // expected 1, actual 2

How do you work around this problem?


回答1:


Use JSON.stringify:

var objects = new Set;

objects.add(JSON.stringify({ a: 1 }));
objects.add(JSON.stringify({ a: 1 }));

alert(objects.size);


来源:https://stackoverflow.com/questions/29272134/javascript-sets-and-value-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!