的JavaScript的indexOf数组没有找到数组的数组 [英] Javascript indexOf for an array of arrays not finding array
问题描述
我有嵌套数组的数组,看起来像这样:
I have an array with nested arrays that looks like this:
var tw = [[3, 0], [11, 0], [3, 14], [11, 14]];
当我试图找到,如果数组 TW
包含数组过去了,我总是得到-1的结果。
When I try and find if the array tw
contains a passed in array, I always get a result of -1.
例如:
var test = $.inArray([3, 0], tw);
var test2 = tw.indexOf([3, 0]);
都返回-1,即使数组中的第一个对象是 [3,0]
我如何找出是否阵列的特定阵列包含在我的阵列?
both return -1, even though the first object in the array is [3,0]
How do I find out if a specific array of arrays is contained in my array?
哦,我只测试了IE9至今。
Oh, and I've only tested it on IE9 so far.
推荐答案
这是因为你正在寻找一个不同的对象。 的indexOf()
使用全等比较(如 ===
运营商)和 [3 ,0] === [3,0]
返回false。
That's because you're searching for a different object. indexOf()
uses strict equality comparisons (like the ===
operator) and [3, 0] === [3, 0]
returns false.
您将需要手动搜索。下面是使用一个使用自定义比较函数(在评论由@ ajax333221建议的改进版本)更宽泛的的indexOf()
函数的一个例子:
You'll need to search manually. Here's an example using a more generic indexOf()
function that uses a custom comparer function (with an improvement suggested by @ajax333221 in the comments):
// Shallow array comparer
function arraysIdentical(arr1, arr2) {
var i = arr1.length;
if (i !== arr2.length) {
return false;
}
while (i--) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function indexOf(arr, val, comparer) {
for (var i = 0, len = arr.length; i < len; ++i) {
if ( i in arr && comparer(arr[i], val) ) {
return i;
}
}
return -1;
}
var tw = [[3, 0], [11, 0], [3, 14], [11, 14]];
alert( indexOf(tw, [3, 0], arraysIdentical) ); // Alerts 0
这篇关于的JavaScript的indexOf数组没有找到数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!