比较两个数组Javascript - 关联 [英] Compare two Arrays Javascript - Associative

查看:156
本文介绍了比较两个数组Javascript - 关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里搜索了一个质量方法来比较javascript中的关联数组。我发现的唯一体面的解决方案是 PHP.JS 项目,它有一些比较数组函数。唯一的问题是这些函数考虑第一个数组作为第二个的关键。在我的情况下,至少两个数组并不总是有相同的密钥或相同的密钥。这会导致函数输出不包含可能不存在于array1中但存在于array2中的键的结果。到目前为止,我唯一想到的是运行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 - 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆