问题描述
我已经搜查这里进行了质量的方法在JavaScript中比较关联数组。唯一体面的解决办法,我发现是里面有一些比较阵列功能项目。唯一的问题是,这些功能考虑的第一个数组为重点,以第二。在我的情况,至少两个数组并不总是有钥匙,也没有相同的密钥相同#。这会导致不包含可能未在ARRAY1已经存在但在数组2存在键的功能,以输出结果。我能想到的,到目前为止的唯一事情是运行两次array_diff_associative()函数的参数翻转,然后将它们结合起来(因为第一个参数再次被用作钥匙,第二,这似乎有问题)。
I have searched on here for a quality method to compare associative arrays in javascript. The only decent solution I have found is the PHP.JS project which has some comparative array functions. The only problem is that these functions consider the first array as the key to the second. In my situation at least both arrays do not always have the same # of keys nor the same keys. This causes the functions to output results that do not include keys that may not have existed in array1 but existed in array2. The only thing I can think of so far is to run the array_diff_associative() function twice with the arguments flipped and then combine them(which seems problematic since the first argument again is used as the keys to the second).
有什么建议?
谢谢你。
Any suggestions?Thank you.
推荐答案
我觉得以下应该做你想要什么:
I think the following should do what you want:
function nrKeys(a) {
var i = 0;
for (key in a) {
i++;
}
return i;
}
function compareAssociativeArrays(a, b) {
if (a == b) {
return true;
}
if (nrKeys(a) != nrKeys(b)) {
return false;
}
for (key in a) {
if (a[key] != b[key]) {
return false;
}
}
return true;
}
这篇关于比较两个数组的Javascript - 联想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!