检查集合是否包含Java列表 [英] Checking if a Set contains a list in Javascript

查看:100
本文介绍了检查集合是否包含Java列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向其中添加列表的集合.

I have a set that I've added a list to.

var a = new Set();
a.add([1]);

现在,我检查a中是否存在[1]:

Now I check if [1] exists in a:

a.has([1]);
> false

基于规范,这可能之所以会发生,是因为如果要比较的两个对象的类型相同:

Based on the spec, this might be happening because if type is same for two objects being compared:

如果x和y指向同一个对象,则返回true.否则,返回 错误.

Return true if x and y refer to the same object. Otherwise, return false.

这也会发生:

[1] == [1]; 
> false

因此,可能是Set .has()正在使用==来比较相等性(尽管不确定).像Java一样,JS中的Set()是否有.contains()方法?

So it might be that the Set .has() is using == for comparing equality (not sure though). Is there a .contains() method for Set() in JS like Java has?

推荐答案

您不能比较数组和对象之类的引用是否相等(可以

You can't compare references like arrays and objects for equality (you can compare values, though).

这样做的方法是,即使值看起来相同,也要对照不同的引用进行检查.

The way you're doing it, you're checking against a different reference, even though the values appear to be the same.

执行以下操作:

var a = new Set();
var b = [1];

a.add(b);

a.has(b); // => true

看看 MDN的平等比较和相同性.

所以可能是Set .has()使用==来比较相等性(虽然不确定)

So it might be that the Set .has() is using == for comparing equality (not sure though)

不一定. [1] === [1](使用严格相等运算符)也会返回false.

Not necessarily. [1] === [1] (using the strict equality operator) also returns false.

像Java一样,JS中的Set()是否有.contains()方法?

Is there a .contains() method for Set() in JS like Java has?

与您想象的方式不同.您可以进行某种深度比较,如该答案的第一个链接中所述.

Not in the way you're imagining it. You can do some sort of deep comparison, as mentioned in the first link in this answer.

这篇关于检查集合是否包含Java列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆