如何知道,如果两个数组有相同的价值观 [英] How to know if two arrays have the same values
本文介绍了如何知道,如果两个数组有相同的价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个数组:一个是从一个Ajax请求,另一个存储按钮,用户点击充满了信息。我用这个code(我充满了样品编号):
VAR数组1 = [2,4]。
变种数组2 = [4,2]。 //它会从用户点击按钮卡梅斯,所以它可能是无序。
array1.sort(); //排序都Ajax和用户信息。
array2.sort();
如果(数组1 ==数组2){
做一点事();
}其他{
doAnotherThing();
}
但它总是给假
,即使两个数组是相同的,但不同的名称。 (我查这在Chrome的JS控制台)。那么,有没有什么办法,我可以知道,如果这两个数组包含相同的?为什么给假
?我怎么能知道它的第一个阵列中的值不会在第二个?
解决方案
Array.prototype.compare =功能(testArr){
如果(this.length = testArr.length!)返回false;
对于(VAR I = 0; I< testArr.length;我++){
如果(本[I] .compare){
如果返回false(这[一] .compare(testArr [I])!);
}
如果(这[一] == testArr [I]!)返回false;
}
返回true;
}变种ARRAY1 = [2,4]。
变种数组2 = [4,2]。
如果(array1.compare(数组2)){
做一点事();
}其他{
doAnotherThing();
}
也许?
I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):
var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
doSomething();
}else{
doAnotherThing();
}
But it always gives false
, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false
? How can I know which values in the first array are not in the second?
解决方案
Array.prototype.compare = function(testArr) {
if (this.length != testArr.length) return false;
for (var i = 0; i < testArr.length; i++) {
if (this[i].compare) {
if (!this[i].compare(testArr[i])) return false;
}
if (this[i] !== testArr[i]) return false;
}
return true;
}
var array1 = [2, 4];
var array2 = [4, 2];
if(array1.compare(array2)) {
doSomething();
} else {
doAnotherThing();
}
Maybe?
这篇关于如何知道,如果两个数组有相同的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文