简体   繁体   English

使用 JavaScript 的 IndexOf 在数组中查找数组

[英]Finding an Array within an Array using IndexOf of JavaScript

I am trying to do a very simple indexOf search without success.我正在尝试做一个非常简单的 indexOf 搜索但没有成功。

I have a two dimensional Array like this:我有一个像这样的二维数组:

var fruits = new Array([]);
fruits.push(["Banana", "Orange", "Apple", "Mango"]);
fruits.push(["Apple", "3Orange", "Amar", "Mango"]);
fruits.push(["Apple", "1Orange", "Amar", "Mango"]);
fruits.push(["Apple", "2Orange", "Amar", "Mango"]);

Now I am creating another Array as below which matches the third record of the above array:现在我正在创建另一个数组,如下所示,它与上述数组的第三条记录相匹配:

var str = new Array([]);
str.push(["Apple", "2Orange", "Amar", "Mango"]);

Now I try to find if str exists in fruits:现在我尝试查找水果中是否存在 str :

var i  = fruits.indexOf( str );
alert(i);

But I returns -1 instead of a valid index value.但我返回 -1 而不是有效的索引值。 What am I doing wrong?我究竟做错了什么?

Edit编辑

I have figured out a very simpler way.我想出了一个非常简单的方法。 Here is what appears to also work:这似乎也有效:

var strFruits = fruits.toString();
var newStr = str.toString();
var i  = fruits.indexOf( str );
alert(i);

This obviously has a pitfall of finding matching value across two records.这显然存在在两个记录中查找匹配值的陷阱。 But in my case I know that won't be possible because of the nature of data set that I am using.但就我而言,我知道这是不可能的,因为我使用的数据集的性质。 Not a good practice as a general solution but in specific cases it might be handy.作为通用解决方案不是一个好习惯,但在特定情况下它可能很方便。

If you pass an object to Array.prototype.indexOf() , then its reference will be verified not its values.如果你将一个对象传递给Array.prototype.indexOf() ,那么它的引用将被验证而不是它的值。 So you have to write a code like this to achieve what you want,所以你必须写这样的代码来实现你想要的,

var str = new Array([]);
str.push(["Apple", "2Orange", "Amar", "Mango"]);
var i  = checkIt(fruits, str[0]);
alert(i);

function checkIt(src, arr){
  arr = arr.toString();
  var ind = -1;
  src.forEach(function(itm,i){
    if(itm.toString() == arr){
      ind = i;
      return;
    }
  });
  return ind;
}

DEMO演示

var arr1 = [1,2,3]; 
var arr2 = [1,2,3];

console.log(arr1 == arr2)   //false
console.log(arr1 === arr2)  //false

and from MDN和来自MDN

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). indexOf() 使用严格相等(与 === 或三重相等运算符使用的方法相同)将 searchElement 与 Array 的元素进行比较。

and 2 objects, even though with same internal properties, wont match.和 2 个对象,即使具有相同的内部属性,也不会匹配。

so to match, you need to compare the array by elements inside it to match it所以要匹配,您需要按数组内部的元素进行比较以匹配它

to compare the elements in the array, you can follow another question in SO, LINK要比较数组中的元素,您可以按照 SO, LINK 中的另一个问题进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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