Check whether an array exists in an array of array

2020-01-24 09:56发布

I'm using JavaScript, and would like to check whether an array exists in an array of arrays.

Here is my code, along with the return values:

var myArr = [1,3];
var prizes = [[1,3],[1,4]];
prizes.indexOf(myArr);
-1

Why?

It's the same in jQuery:

$.inArray(myArr, prizes);
-1

Why is this returning -1 when the element is present in the array?

标签: javascript
8条回答
ら.Afraid
2楼-- · 2020-01-24 10:23

Because both these methods use reference equality when operating on objects. The array that exists and the one you are searching for might be structurally identical, but they are unique objects so they won't compare as equal.

This would give the expected result, even if it's not useful in practice:

var myArr = [1,3];
var prizes = [myArr,[1,4]];
prizes.indexOf(myArr);

To do what you wanted you will need to write code that explicitly compares the contents of arrays recursively.

查看更多
我命由我不由天
3楼-- · 2020-01-24 10:24

Because javascript objects are compared by identity, not value. So if they don't reference the same object they will return false.

You need to compare recursively for this to work properly.

查看更多
登录 后发表回答