JavaScript sets and value objects [duplicate]

2019-08-06 15:54发布

This question already has an answer here:

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条回答
Anthone
2楼-- · 2019-08-06 16:47

Use JSON.stringify:

var objects = new Set;

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

alert(objects.size);

查看更多
登录 后发表回答