【问题标题】:Using indexOf to get index of array in a collection of arrays (Javascript)使用 indexOf 获取数组集合中的数组索引(Javascript)
【发布时间】:2017-02-20 21:43:49
【问题描述】:

在数组集合中查找数组索引的最佳方法是什么?为什么 indexOf() 不返回正确的索引?我猜这与对象相等有关?

我已经看到其他解决方案遍历集合并返回满足相等性检查时达到的索引,但我仍然很好奇为什么 indexOf() 不做同样的事情。此外,由于 IE 11 支持(一如既往),我无法使用 ES6 的 find / findIndex。我在下面包含了我的测试代码。非常感谢。

var numbers = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] ];

function getIndex (numbersToTest) {
  return numbers.indexOf(numbersToTest);
};

function test() {
  console.log( getIndex( [1, 2, 3, 4, 5, 6] ) ); // Except 0
  console.log( getIndex( [7, 8, 9, 10, 11, 12] ) ); // Expect 1
  console.log( getIndex( [2, 1, 3, 4, 5, 6] ) ); // Expect -1 (not in same order)
}

test();

【问题讨论】:

  • 你说得对,它与对象相等有关,因为 [] == []false
  • 我有这个问题的答案,在这种情况下,可以将数组作为字符串进行比较,jsfiddle.net/dbpLenwu
  • @trincot 我不相信这是一个重复的问题,因为我正在寻找找到数组索引的最佳方法,并且还想要一些关于为什么 indexOf 不起作用的背景信息(不是主要讨论点)。非常感谢。
  • 看我上面的 jsfiddle 可能对你的情况有用@poolts
  • @trincot 仍然认为它的关联多于重复,但如果您仍然不这么认为,请关闭它。

标签: javascript arrays indexof


【解决方案1】:

对象引用(包括数组引用)作为引用值进行比较;只有当两个引用都指向完全相同的对象时,一个对象引用才等于另一个对象引用。在您的情况下,不会根据数组的 content 进行比较。即使您传入的那些数组具有相同的值,它们也是不同的数组,因此不等于原始列表中的任何数组。

相反,您需要使用Array#find(查找条目)或Array#findIndex(查找条目的索引)之类的东西,传入一个回调,将numbers 中的数组与numbersToTest 进行比较以查看如果它们是等效的数组。 This question's answers 讨论有效比较数组是否等价的各种方法。

例如:

var numbers = [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] ];

function getIndex (numbersToTest) {
  return numbers.findIndex(function(entry) {
    // Simple comparison that works for an array of numbers
    return entry.length === numbersToTest.length && entry.every(function(number, index) {
      return numbersToTest[index] === number;
    });
  });
};

function test() {
  console.log( getIndex( [1, 2, 3, 4, 5, 6] ) ); // Expect 0
  console.log( getIndex( [7, 8, 9, 10, 11, 12] ) ); // Expect 1
  console.log( getIndex( [2, 1, 3, 4, 5, 6] ) ); // Expect -1 (not in same order)
}

test();

请注意,Array#findArray#findIndex 都是新的(ES2015,又名“ES6”),但可以为较旧的 JavaScript 引擎进行 polyfill。

【讨论】:

  • 谢谢@TJCrowder 我欠你一杯啤酒:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多