简体   繁体   English

如何在数组数组中找到元素的索引?

[英]How can I find the index of an element, in an array of arrays?

Here is a simple example of an array that contains at least one other array. 这是一个包含至少一个其他数组的数组的简单示例。 I want a way to find the index of an array, within an array. 我想要一种在数组中查找数组索引的方法。 However, the code I have below does not work: 但是,我下面的代码不起作用:

var arr = [1,2,[1,2]];
console.log(arr.indexOf([1,2])); //-> -1

for (var i = 0; i < arr.length; i++) {
  if (arr[i] == [1,2])
    return 'true' // does not return true
}

Intuitively, this should work but does not: 直观上,这应该起作用,但是不起作用:

if ([1,2] == [1,2]) return 'true' // does not return true

Can someone explain why it does not work, and offer an alternative solution? 有人可以解释为什么它不起作用,并提供替代解决方案吗? Thanks! 谢谢!

No, but you can check it yourself: 不,但是您可以自己检查:

var a = [1,2], b = [1,2];

a.length === b.length && a.every(function(x,y) { return x === b[y]; });

Arrays in JavaScript are compared by reference not by value. JavaScript中的数组是按引用而不是按值进行比较的。 That is why 这就是为什么

console.log([1,2] == [1,2])

returns false . 返回false

You need a custom function that could compare arrays. 您需要一个可以比较数组的自定义函数。 If you want to check only the first level of nesting you can use this code: 如果只想检查嵌套的第一级,则可以使用以下代码:

var compareArrays = function(a, b) {
    if (a.length !== b.length) {
        return false;
    }

    for (var i = 0, len = a.length; i < len; i++) {
        if (a[i] !== b[i]) {
            return false;
        }
    }

    return true;
}

You are confusing the definitions of similar objects vs. the same object. 您会混淆相似对象与相同对象的定义。 Array.prototype.indexOf() compares the objects using the strict equality comparison algorithm . Array.prototype.indexOf()使用严格相等比较算法比较对象。 For (many) objects, this means an object reference comparison (ie the object's unique identifier, almost like its memory address). 对于(许多)对象,这意味着对象引用比较(即对象的唯一标识符,几乎类似于其内存地址)。

In your example above, you are trying to treat two similar arrays as though they were the same array, and that's why it doesn't work. 在上面的示例中,您试图将两个相似的数组视为同一数组,这就是为什么它不起作用的原因。 To do what you are trying to do, you need to use the same array. 要执行您想做的事情,您需要使用相同的数组。 Like this: 像这样:

var testArr = [1,2]; //a specific object with a specific reference
var arr = [1,2,testArr]; //the same array, not a different but similar array
console.log(arr.indexOf(testArr)); //returns 2

If you just want to know where arrays occur in the parent array, use Array.isArray() : 如果只想知道父数组中的数组,请使用Array.isArray()

...
if(Array.isArray(arr[i])) {
    //do something
}
...

Hopefully that helps! 希望有帮助!

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

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