javascript按值而不是引用来比较数组

时间:2017-05-14 18:15:58

标签: javascript arrays equals

我必须在JS中比较2个这样的类型数组。

var array1 = [

  null,
  "Marvel",
  "2.0.17",
  {
    name: "Hulk",
    color: "green",
    age: 31,
    abilities: ["crash", "smash"]
  },
  {
    name: "Iron Man",
    age: 35,
    stillAlive: true
  },
  ["Captain America", "Thor", "Captain Marvel"]
];


var array2 = [

  null,
  "Marvel",
  "2.0.17",
  {
    name: "Hulk",
    color: "green",
    age: 31,
    abilities: ["crash", "smash"]
  },
  {
    name: "Iron Man",
    age: 35,
    stillAlive: true
  },
  ["Captain America", "Thor", "Captain Marvel"]
];


function deepEquals(array1, array2) {
  //check if arguments are arrays
  if (!Array.isArray(array1) && !Array.isArray(array2)) {
    console.log("arguments are not arrays" + "\n")
    return false;
  }

  //check arrays by lenghts
  if (array1.length !== array2.length) {
    console.log("arrays lenghts are different" + "\n");
    return false;
  } else {
    for (var i = 0; i < array1.length; i++) {
      if (typeof(array1[i]) !== "object" || typeof(array2[i]) !== "object" ||
        (array1[i] === null) || (array1[2] === null)) {

        //compare primitive values
        var primitiveCmp = comparePrimitives(array1[i], array2[i])
        if (primitiveCmp == false) {
          console.log("primitive values are different");
          return false;
        }
      } else {

        //compare pbjects
        var objCmp = compareObjects(array1[i], array2[i]);
        if (objCmp == false) {
          console.log("objects are different");
          return false;
        }

      }
    }

    console.log("arrays are equals" + "\n");
    return true;
  }
}


function comparePrimitives(var1, var2) {
  if (var1 !== var2) {
    console.log("primitive values are different: " + var1 + " and: " + var2 + "\n")
    return false;
  }

}

function compareObjects(o1, o2) {

  var aProps = Object.getOwnPropertyNames(o1);
  var bProps = Object.getOwnPropertyNames(o2);

  if (aProps.length != bProps.length) {
    console.log("objects has diff count of property");
    return false;
  }

  for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i];

    // If values of same property are not equal,
    // objects are not equivalent
    if (o1[propName] !== o2[propName]) {
      console.log("objects are not equals they have different values of properties -> " +
        o1[propName] + " and-> " + o2[propName]);
      return false;
    }
  }

}



console.log(deepEquals(array1, array2));

当我打电话给我时,我会收到:

  

对象不等于它们具有不同的属性值 - &gt;崩溃,粉碎和 - >碰撞,粉碎
  对象是不同的   假

我该如何解决这个问题?我需要按值而不是通过引用进行比较。

0 个答案:

没有答案