javascript indexOf() 不断返回-1

标签 javascript arrays indexof

我有一个像这样的数组

var a = [[1, 0], [3, 0], [5, 0], [7, 0]];

我正在运行一行非常简单的indexOf()。然而,尽管我使用的测试值确实存在于数组中,但我一直得到 -1。

var i = a.indexOf([1, 0]);
console.log("INDEX: ", i);

我是不是哪里搞错了?

最佳答案

您可以使用#findIndex()#every()查找 outer 数组内 inner 数组的索引 - 请参阅下面的演示:

var a = [[1, 0], [3, 0], [5, 0], [7, 0]];
var search = [1,0]; // array to get index of from the 'a'

var i = a.findIndex(function(n) {
  return search.every(function(p,q) { 
    return p === n[q]
  });
});
console.log("INDEX: ", i);

以及更简单的ES6风格:

var a = [[1, 0], [3, 0], [5, 0], [7, 0]];
var search = [1, 0]; // array to get index of from the 'a'

var i = a.findIndex(n => search.every((p, q) => p === n[q]));
console.log("INDEX: ", i);

关于javascript indexOf() 不断返回-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778708/

相关文章:

javascript - 为什么在 iPhone 上查看网站时 MapBox-GL-JS map 不能平移或滚动?

mysql extract_json 数组中的值

javascript - 如何使用 javascript 在 getSelection() 中查找所选文本的索引?

javascript - 通过 "."识别 "if ... if"并且字符串中没有空格

jQuery Ajax 如何将responseText 作为变量传递给indexOf?

javascript - 如何确保 if 循环在按顺序运行下一个 if 循环之前等待并接收结果

javascript - 如何在页面刷新时在 JavaScript 中删除后添加子元素

javascript - 异步函数无法使用 JQuery 工作

c++ - 在 VC++ 中,数组的长度不会在运行时得到验证吗?

c++ - Arduino C++,奇怪的数组行为