javascript 检查数组中是否存在数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19543514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether an array exists in an array of arrays?
提问by Richard
I'm using JavaScript, and would like to check whether an array exists in an array of arrays.
我正在使用 JavaScript,并想检查数组中是否存在一个数组。
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:
在 jQuery 中也是一样:
$.inArray(myArr, prizes);
-1
Why is this returning -1 when the element is present in the array?
当元素存在于数组中时,为什么返回 -1?
采纳答案by Zeta
Because [1,3] !== [1,3]
, since objects will only equal if they reference the same object. You need to write your own search routine:
因为[1,3] !== [1,3]
,因为对象只有在引用同一个对象时才会相等。您需要编写自己的搜索例程:
function searchForArray(haystack, needle){
var i, j, current;
for(i = 0; i < haystack.length; ++i){
if(needle.length === haystack[i].length){
current = haystack[i];
for(j = 0; j < needle.length && needle[j] === current[j]; ++j);
if(j === needle.length)
return i;
}
}
return -1;
}
var arr = [[1,3],[1,2]];
var n = [1,3];
console.log(searchForArray(arr,n)); // 0
References
参考
- Using the Equality Operators:
If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.
- 使用相等运算符:
如果两个操作数都是对象,则将它们作为对象进行比较,并且仅当两者都引用同一个对象时,相等性测试才为真。
回答by aHyman13
You can use this
你可以用这个
var a = [ [1,2] , [3,4] ];
var b = [1,2];
a = JSON.stringify(a);
b = JSON.stringify(b);
then you can do just an indexOf() to check if it is present
那么你可以只做一个 indexOf() 来检查它是否存在
var c = a.indexOf(b);
if(c != -1){
console.log('element present');
}
回答by Jon
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.
要执行您想要的操作,您需要编写代码以递归方式显式比较数组的内容。
回答by Nina Scholz
You could iterate the array of arrays with Array#some
and then check every item of the inner array with the single array with Array#every
.
您可以迭代数组数组,Array#some
然后使用单个数组检查内部数组的每个项目Array#every
。
var array = [1, 3],
prizes = [[1, 3], [1, 4]],
includes = prizes.some(a => array.every((v, i) => v === a[i]));
console.log(includes);
回答by Wolph
Because javascript objects are compared by identity, not value. So if they don't reference the same object they will return false.
因为 javascript 对象是按身份而不是值进行比较的。因此,如果它们不引用相同的对象,它们将返回 false。
You need to compare recursively for this to work properly.
您需要递归比较才能正常工作。
回答by Hilmi
first define a compare function for arrays
首先为数组定义一个比较函数
// attach the .compare method to Array's prototype to call it on any array
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0; i < this.length; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
second just find the array with
其次只需找到数组
prizes.filter(function(a){ return a.compare(myArr)})
NOTE: check the browser compatibility for array.filter
注意:检查浏览器对array.filter 的兼容性
回答by guypursey
Assuming you are only dealing with a two-dimensional array (you mention an "array of arrays" but nothing deeper than that), this non-recursive code should do what you need.
假设你只处理一个二维数组(你提到了一个“数组数组”,但没有比这更深的了),这个非递归代码应该可以满足你的需求。
var compare_arrays = function (array_a, array_b) {
var rtn = true,
i, l;
if (array_a.length === array_b.length) {
for (i = 0, l = array_a.length; (i < l) && rtn; i += 1) {
rtn = array_a[i] === array_b[i];
}
} else {
rtn = false;
}
return rtn;
},
indexOfSimilarArray = function (arrayToFind, arrayToSearch) {
var i = arrayToSearch.length,
chk = false;
while (i && !chk) {
i -= 1;
chk = compare_arrays(arrayToFind, arrayToSearch[i]);
}
return i;
};
// Test
var myArr = [1,3];
var prizes = [[1,3],[1,4]];
indexOfSimilarArray(myArr, prizes);
JSFiddle: http://jsfiddle.net/guypursey/V7XpE/. (View the console to see the result.)
JSFiddle:http: //jsfiddle.net/guypursey/V7XpE/。(查看控制台以查看结果。)
回答by Cumulo Nimbus
function doesArrayOfArraysContainArray (arrayOfArrays, array){
var aOA = arrayOfArrays.map(function(arr) {
return arr.slice();
});
var a = array.slice(0);
for(let i=0; i<aOA.length; i++){
if(aOA[i].sort().join(',') === a.sort().join(',')){
return true;
}
}
return false;
}
Worth noting:
值得注意:
aOA[i].sort().join(',') === a.sort().join(',')
is a useful way to check for arrays that contain the same values in the same order, but are references to different objects.array.slice(0)
creates a non-referential copy of the original 2D array.However, to create a copy of a 3D array
arrayOfArrays.slice(0)
does not work; the reference chain will still be present. In order to create a non-referential copy the.map
function is necessary.
aOA[i].sort().join(',') === a.sort().join(',')
是检查包含相同顺序的相同值但引用不同对象的数组的有用方法。array.slice(0)
创建原始二维数组的非引用副本。但是,创建 3D 数组的副本
arrayOfArrays.slice(0)
不起作用;参考链仍然存在。为了创建非引用副本,该.map
函数是必要的。
If you don't create these non-referential array copies you can really run into some tough to track down issues. This function should operate as a conditional and not effect the initial objects passed in.
如果您不创建这些非引用数组副本,您可能真的会遇到一些难以追踪的问题。此函数应作为条件操作,而不影响传入的初始对象。
Javascript is one fickle mistress.
Javascript 是一位善变的情妇。