问题
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