乐趣区

关于javascript:Js-比较两个对象的键名与键值是否相等

文中还应用了 sort 函数来排序,这样做的益处是只管对象程序不统一也能够比拟相等

  let obj = {
        leftDom1: 'rightDom1',
        leftDom2: 'rightDom1',
        leftDom3: 'rightDom3',
        leftDom4: 'rightDom2',
      };
      let obj2 = {
        leftDom2: 'rightDom1',
        leftDom3: 'rightDom3',
        leftDom4: 'rightDom2',
        leftDom1: 'rightDom1',
      };
      function compareObjects(obj1, obj2) {const keys1 = Object.keys(obj1).sort();
        const keys2 = Object.keys(obj2).sort();
        if (keys1.length !== keys2.length) {return false;}
        for (let i = 0; i < keys1.length; i++) {if (keys1[i] !== keys2[i] || obj1[keys1[i]] !== obj2[keys2[i]]) {return false;}
        }

        return true;
      }

      console.log(compareObjects(obj, obj2)); // true
退出移动版