【问题标题】:Array.indexOf always returns -1 when search for array in array在数组中搜索数组时,Array.indexOf 总是返回 -1
【发布时间】:2021-07-24 03:40:20
【问题描述】:

我有一个数组数组:

var BigArray = [[1,2,3,"Foo"],[4,5,6,"Bar"], [1,2,3,"Baz"]];

我想找到[1,2,3,"Foo"] 的索引。当我执行console.log(BigArray.indexOf([1,2,3,"Foo"])) 时,它总是返回-1,即使[1,2,3,"Foo"] 确实存在于BigArray 中。有解决办法吗?

【问题讨论】:

  • 如果以下答案有用,请点击其左侧的点赞按钮 (▲)。如果有人回答了您的问题,请单击复选标记 (✓) 接受它(一旦系统允许)。这样其他人就知道你已经(充分地)得到了帮助。另见What should I do when someone answers my question?

标签: javascript arrays nested-lists


【解决方案1】:

您可以做到这一点不必使用外部库:

const BigArray = [[1,2,3,"Foo"],[4,5,6,"Bar"], [1,2,3,"Baz"]],
      lookFor=[4,5,6,"Bar"];

// the comparison === between two objects will only be true
// if these are the same objects (ONE and the same!)
// === will NOT compare their contents!

console.log(BigArray.indexOf(lookFor)) // -1

// if you want to compare their contents you could convert
// them to JSOn representations:

console.log(BigArray.map(JSON.stringify).indexOf(JSON.stringify(lookFor))) // 1

【讨论】:

    【解决方案2】:

    来自MDN

    indexOf() 使用strict equality(与=== 或三等号运算符使用的方法相同)将searchElement 与数组元素进行比较。

    而且,严格相等会为不同的对象生成false(即使它们的值相同),因为它会根据检查primitivesSymbol 除外)和对象引用 用于对象。

    Example:

    console.log("hello" === "hello"); // true
    
    const object1 = { name: "hello" };
    const object2 = { name: "hello" };
    
    console.log(object1 === object2); // false
    console.log(object1 === object1); // true
    

    因此,您无法使用Array.prototype.indexOf() 解决您当前的问题,但您可以使用lodash 中的findIndexisEqual 方法(您也可以尝试underscore):

    使用 lodash:

    var BigArray = [
      [1, 2, 3, "Foo"],
      [4, 5, 6, "Bar"],
      [1, 2, 3, "Baz"]
    ];
    
    console.log(_.findIndex(BigArray, function(o) {
      return _.isEqual(o, [4, 5, 6, "Bar"]);
    }));
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

    【讨论】:

      【解决方案3】:

      当您尝试使用indexOf 时,您正在使用一个数组来查找另一个数组,这不起作用,您必须使用一个标量值。

      你可以使用一个简单的 for 循环来完成你想要的。

      const BigArray = [[1,2,3,"Foo"],[4,5,6,"Bar"], [1,2,3,"Baz"]];
      let i;
      let index = -1;
      
      for(i = 0; i < BigArray.length; i++) {
          if(BigArray[i].includes('Foo')) {
              index = i;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-06
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多