Reputation: 21
Why does this code throw and out-of-bounds error, it seems like it should work fine.
var a = [[[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]]];
var b = [3,4];
console.log(jQuery.inArray(b,a[0][0]));
Upvotes: 2
Views: 618
Reputation: 268344
You can't find it, because it's not there. In JavaScript, just because two arrays have similar contents doesn't mean that the arrays themselves are equal. Try the following in your console:
[3,4] === [3,4];
The output will be that of false
, since two similar arrays are not the same array. If you wanted this code to work, you'd have to actually put one array into another, like this:
var a = [3,4];
var b = [5,a]; // [5,[3,4]]
jQuery.inArray(a, b); // a is found at index 1
If you merely want to check for the presence of a similar array within the haystack, you could stringify the entire needle and haystack, and look for the substring:
var needle = JSON.stringify([3,4]);
var haystack = JSON.stringify([[3,4],[5,6]]);
haystack.indexOf(needle); // needle string found at index 1
You should note however that the index returned is the index the stringified representation is found at, and not the actual index the array is found at within the haystack. If you wanted to find the true index of the array, we'd have to modify this logic just a bit:
var needle = JSON.stringify([3,4]),
haystack = [[3,4],[5,6]],
position = -1,
i;
for (i = 0; i < haystack.length; i++) {
if (needle === JSON.stringify(haystack[i])) {
position = i;
}
}
console.log(position); // needle found at index 0
Run this code: http://jsfiddle.net/DTf5Y/
Upvotes: 3
Reputation: 8006
The problem is that you have too many square braces.
var a = [[[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]]];
var b = [3,4];
console.log(jQuery.inArray('b',a[0][0]));
should be
var a = [[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]];
var b = [3,4];
console.log(jQuery.inArray('b',a[0][0]));
Upvotes: 0