【问题标题】:Creating a deepEqual function in JavaScript在 JavaScript 中创建 deepEqual 函数
【发布时间】:2017-02-02 14:34:15
【问题描述】:

我知道有多个基于此的问题,但我正在尝试创建自己的版本。我也知道还有一个 lodash 版本。

这是我当前的代码:

var deepEqual = function(obj1, obj2) {
  console.log(obj1, obj2);
  // if they reference the same object in memory, then they are the same
  if (obj1 === obj2) {
    return true; 
  }

  if (Array.isArray(obj1) && Array.isArray(obj2) &&
      obj1.length === obj2.length) {
    for (var i = 0; i < obj1.length; i++) {
      if (!deepEqual(obj1[i], obj2[i])) {
        return false;
      }
    }
  }

  // if they don't have the same length, then not equivalent
  if ( Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
  }

  // if they don't have the same properties, then not equivalent
  for (var key in obj1) {
    if (!(key in obj2) || !deepEqual(obj1[key], obj2[key])) { // line 24
      return false;
    }
  }

  return true;
}

当我测试时

var obj = {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}; 
console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}));

它返回true,但是当我将第二个参数中的'y' 更改为'THIS_IS_NOT_y' 时:我得到了

console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'THIS_IS_NOT_y'}}, ['!']]}))

我明白了:

TypeError: invalid 'in' operand obj2 (line 24 in function deepEqual) 

我不知道如何解决这个问题。

除了修复上述错误之外,我的代码中是否还缺少其他类型/情况?

【问题讨论】:

  • for(var key in "y"){...}"0" 迭代为一个可枚举键,"0" in "z" 导致语法错误。您可以区分原始类型和对象,并直接比较原始类型。

标签: javascript arrays object comparison comparison-operators


【解决方案1】:
    function deepEqual(obj1,obj2){

      if(obj1 === obj2) {   //Same object reference
            return true; }

      if( Object.keys(obj1).length !== Object.keys(obj2).length) {
            return false; }  // If length is not same objects are not


     for(var i in obj1){
       if((obj1[i] !== null && typeof obj1[i] === 'object') && 
          (obj2[i] !== null && typeof obj2[i] === 'object')){

               return deepEqual(obj1[i],obj2[i]);}

       else if(((typeof obj1[i]) != 'object') && 
               ((typeof obj1[i]) != 'object')){
                     if(obj1[i]===obj2[i]){
                        return true; // These are identical values!
                      }
                }

       else if(obj1[i]==null && obj2[i]==null)
                { return true; } 

       else return false; //If they are not equal 
      }
   }         
    var obj = {here: {is: "an"}, object: 2, here: "is", an: ['a','r',{r: {a:'y'}}, ['!']]}; 

    console.log(deepEqual(obj, {here: {is: "an"}, object: 2, here:    "is", an: ['a','r',{r: {a:'THIS_IS_NOT_y'}}, ['!']]}));

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多