Why does this index of a two dimensional array return -1 [duplicate]

老子叫甜甜 提交于 2021-02-20 00:23:01

问题


I have the following code:

alert( [[0,1],[1,0]].indexOf([0,1]) );

And even though the array [0,1] is an element of the two-dimensional array, I get a value of '-1' returned. What have I done wrong in life?


回答1:


It doesn't find your element because [0, 1] and [0, 1] are not equal in the same way that 4 and 4 are.

console.log(4 === 4); // true
console.log([0, 1] === [0, 1]); // false

When you do an equality check for things with a type of object, then Javascript uses what's known as reference equality. It checks whether the two objects are actually the same instance.

var a = [0, 1];
var b = [1, 0];
var arr = [a, b];

console.log(arr.indexOf(a)); // 0
console.log(a === arr[0]); // true

Alternatively you can write your own search function using a deep equality check.

function deepSearch(arr, element) {
  for(var index = 0; index < arr.length; index++) {
    if(deepEqual(arr[index], element)) {
      return index;
    }
  }

  return -1;
}



回答2:


Short answer: Because [0,1] === [0,1] is false.

According to .indexOf documentation,

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

You can use a trick and serialize your subarrays and target item.
It works, because [0,1] !== [0,1], but "[0,1]" === "[0,1]":

Array.prototype.indexOfForArrays = function(search)
{
  var searchJson = JSON.stringify(search); // "[0,1]"
  var arrJson = this.map(JSON.stringify); // ["[3,4]", "[0,1]", "[1,0]"]

  return arrJson.indexOf(searchJson);
};

document.body.innerText = [[3,4], [0,1], [1,0]].indexOfForArrays([0,1]); 

There are some other methods. This Stackoverflow question may be useful.



来源:https://stackoverflow.com/questions/34170558/why-does-this-index-of-a-two-dimensional-array-return-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!