Compare two Arrays Javascript - Associative

后端 未结 3 498
醉梦人生
醉梦人生 2021-01-17 22:30

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 comparat

3条回答
  •  清歌不尽
    2021-01-17 23:10

    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;
    }
    

提交回复
热议问题