JavaScript indexOf没有返回好结果

时间:2018-01-23 12:21:51

标签: javascript arrays indexing

我试图通过函数indexOf找到我的数组的索引,但是我无法得到正确的结果。

var points =[
    ["2.408","38.8"],
    ["2.410","38.8"],
    ["2.410","38.76"]
];
var position = points.indexOf(["2.408","38.8"]);

我认为它应该返回0而不是-1,所以我把这两个阵列摧毁了。

console.log(points[0]===["2.408","38.8"])

然后我弄错了。

我不明白为什么不是真的。

我很感激您的建议......

3 个答案:

答案 0 :(得分:2)

您可以使用findIndexevery方法执行此操作。

var points = [["2.408", "38.8"], ["2.410", "38.8"],["2.410", "38.76"]];
const arr = ["2.408","38.8"];

const i = points.findIndex(a => {
  return a.length == arr.length && arr.every((e, i) => a[i] == e)
})

console.log(i)

答案 1 :(得分:1)

您没有搜索相同的数组。

创建数组时,您正在创建一个Object并在变量中存储对它的引用。当您搜索阵列数组时,查找逻辑将通过引用进行比较,而不是通过深度值进行比较。这就是indexOf给你-1的原因;你实际上并没有在阵列数组中搜索任何东西。



const a = ["foo", "bar"],
  b = ["foo", "bar"];

const arr = [a];

console.log(arr.indexOf(["foo", "bar"])); // -1, not the right reference
console.log(arr.indexOf(b)); // -1, again, not the right reference
console.log(arr.indexOf(a)); // 0, the right reference




答案 2 :(得分:0)

您可以使用findIndex和辅助函数来创建与任何数组的比较。



    var allElementsEquals = function(refArray) {
        return function(array) {
          if (array.length !== refArray.length) return false;
    	  for (var i = 0; i < array.length; i++) { if (array[i] !== refArray[i]) return false; }
          return true
        }
    }

    // test 1 
    var points =[
        ["2.408","38.8"],
        ["2.410","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);


    // test 2
    var points =[
        ["2.410","38.8"],
        ["2.408","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);
    
    // test 3
        var points =[
        ["2.410","38.8"],
        ["2.409","38.8"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);

    // test 4
        var points =[
        ["2.410","38.8"],
        ["38.8","2.408"],
        ["2.410","38.76"]
    ];
    var position = points.findIndex(allElementsEquals(["2.408","38.8"]));
    console.log(position);
&#13;
&#13;
&#13;