I have a set that I've added a list to.
var a = new Set();
a.add([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:
Return true if x and y refer to the same object. Otherwise, return false.
And this also happens:
[1] == [1];
> false
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?
The Set.has() method in JavaScript is used to check whether an element with a specified value exists in a Set or not. It returns a boolean value indicating the presence or absence of an element with a specified value in a Set.
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.
contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
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.
Do something like this:
var a = new Set();
var b = [1];
a.add(b);
a.has(b); // => true
Take a look at MDN's Equality comparisons and sameness.
So it might be that the Set .has() is using == for comparing equality (not sure though)
Not necessarily. [1] === [1]
(using the strict equality operator) also returns false
.
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.
although both [1]
's have the same value, they are two different arrays, pointing to two different locations in memory, hence they are not equal.
you can use a basic loop to check
for (let item of mySet.keys()) {
item.toString() == [1].toString();
//true on match.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With