简体   繁体   中英

Find an Array in a two dimensional Array

Why does indexOf give -1 in this case:

   var q = ["a","b"];
   var matchables = [["a","b"],["c"]];
   matchables.indexOf(q);

How should I establish if the value stored in q can be found in matchables ?

Because indexOf uses === as the comparison flag.

=== operating on non-primitives (like Array s) checks for if the Objects are identical. In JavaScript, Objects are only identical if they reference the same variable.

Try this to see what I mean (in console):

([])===([])

It returns false because they do not occupy the same space in memory.

You need to loop and use your own equality check for anything other than true/false/string primitive/number primitive/null/undefined

// Only checks single dimensional arrays with primitives as elements!
var shallowArrayEquality = function(a, b){
    if(!(a instanceOf Array) || !(b instanceof Array) || a.length !== b.length)
      return false;
    for(var ii=0; ii<a.length; ii++)
      if(a[ii]!==b[ii])
        return false;
    return true;
};

var multiDimensionalIndexOf = function(multi, single){
   for(var ii=0; ii<a.length; ii++)
      if(shallowArrayEquality(multi[ii], single) || multi[ii] === single)
        return ii;
   return -1;
};

multiDimensionalIndexOf(matchables, q); // returns 0

Because

["a","b"] === ["a","b"]

is false .

The way to get it to work would Be this:

var q = ["a", "b"];
var matchables = [q, ["c"]];
matchables.indexOf(q);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM