【发布时间】: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