Checking for a set in a list in Javascript

I have a kit that I added to the list.

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

Now I check if exists [1]in a:

a.has([1]);
> false

Based on the specification, this can happen because if the type is the same for two compared objects:

Returns true if x and y refer to the same object. Otherwise, return the lie.

And this also happens:

[1] == [1]; 
> false

Therefore, it may be that Set .has()uses ==equality to compare (not sure though). Is there a way .contains()for Set () in JS like Java?

+4
source share
3 answers

, ( , ).

, , .

- :

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

a.add(b);

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

MDN Equality.

, Set.has() == ( , )

. [1] === [1] ( ) false.

.contains() Set() JS, Java?

, . - , .

+10

[1] , , , .

for (let item of mySet.keys()) {
  item.toString() == [1].toString();
  //true on match.
}
+4

If you compare two arrays with the "==" operator, they will never be equal. These are different instances.

If you want to use an array object:

  • Determine how two arrays are compared.
  • Subclass Set and override the "has" method.

.

function eqArray (a1, a2) {
    if (!(a1 instanceof Array && a2 instanceof Array))
      return false;
    if ( a1.length != a2.length)
      return false;
    for (var i = 0, n=a1.length; i < n; i++) {
        if (a1[i] instanceof Array && a2[i] instanceof Array) {
            if (!eqArray(a1[i], a2[i]))
                return false;       
        }           
        else if (a1[i] != a2[i])
            return false;       
    }       
    return true;
}

function MySet(elems) {
  var set = new Set (elems);
  set.__proto__ = MySet.prototype;
  return set;
}

MySet.prototype = new Set;

MySet.prototype.has = function (elem) {
   if (elem instanceof Array){
      for (var v of this) {
        if (v instanceof Array && eqArray(elem,v))
         return true;
      }
      return false;
   }else {
      return Set.prototype.has.call (this, elem);
   }
}

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

a.has([1]); //true

eqArray([1],[1]); //true
0
source

Source: https://habr.com/ru/post/1651337/


All Articles