简体   繁体   English

在反应中比较两个 state arrays 如果它们相等,则不会返回 boolean (真)

[英]Comparing two state arrays in react will not return a boolean (True) if they are equal

When I am comparing two arrays from my state, if they are equal I want to change a third state boolean variable to "true".当我比较我的 state 中的两个 arrays 时,如果它们相等,我想将第三个 state Z84E2C5“C64F38FA28BA73”更改为“C64F38FA28BA73” However when the two arrays are equal, the if statement I created to detect it does not return a "true".但是,当两个 arrays 相等时,我为检测它而创建的 if 语句不会返回“true”。

I am doing this within a setInterval(), i dont know if that has anything to do with this problem...我在 setInterval() 中执行此操作,我不知道这是否与此问题有关...

class DisplaySort extends Component {
  constructor(props) {
    super(props);
    this.state = {
      array: [1, 2, 3],
      array2: [1, 2, 3],
      istrue: false,
     };
    this.compare = this.compare.bind(this);
};

render() {
   return (
     <div>
       <button onClick={this.compare}>Compare</button>
     </div>
    );
  }

compare(e) {
    this.myInterval = setInterval(() => {
      let a = this.state.array.slice();
      let b = this.state.array2.slice();
      if (a === b) {
        this.setState({ istrue: true });
        clearInterval(this.myInterval);
      }

(The set interval is being used for another operation in the application (aka there is an else statement after the if) but excluded for brevity's sake) (设置的时间间隔被用于应用程序中的另一个操作(也就是在 if 之后有一个 else 语句),但为简洁起见被排除在外)

If you compare arrays that way, you will always get false, unless you check a === a如果你这样比较 arrays ,你总是会得到错误的,除非你检查a === a

Here is a function to check equality between objects/arrays, also if nested:这是一个 function 来检查对象/数组之间的相等性,如果嵌套也是如此:

function isEqual(value, other) {
    // Get the value type
    var type = Object.prototype.toString.call(value);

    // If the two objects are not the same type, return false
    if (type !== Object.prototype.toString.call(other)) {
        return false;
    }

    // If items are not an object or array, return false
    if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
        return false;
    }

    // Compare the length of the length of the two items
    var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
    var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
    if (valueLen !== otherLen) {
        return false;
    }
    // Compare two items
    var compare = function (item1, item2) {

        // Get the object type
        var itemType = Object.prototype.toString.call(item1);

        // If an object or array, compare recursively
        if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
            if (!isEqual(item1, item2)) {
                return false;
            }
        }

        // Otherwise, do a simple comparison
        else {

            // If the two items are not the same type, return false
            if (itemType !== Object.prototype.toString.call(item2)) return false;

            // Else if it's a function, convert to a string and compare
            // Otherwise, just compare
            if (itemType === '[object Function]') {
                if (item1.toString() !== item2.toString()) return false;
            } else {
                if (item1 !== item2) return false;
            }

        }
    };

    // Compare properties
    if (type === '[object Array]') {
        for (var i = 0; i < valueLen; i++) {
            if (compare(value[i], other[i]) === false) return false;
        }
    } else {
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (compare(value[key], other[key]) === false) return false;
            }
        }
    }

    // If nothing failed, return true
    return true;

}

This is not written by me, I google it long ago.这不是我写的,我很久以前google了。

You can simply use this:你可以简单地使用这个:

  if(JSON.stringify(a) == JSON.stringify(b)){YOUR CODE HERE};

NOTE: this solution is good for your use case but not for complex array values.注意:此解决方案适用于您的用例,但不适用于复杂的数组值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM