JS 判断两个数组或对象是否相同

JS 判断两个数组是否相同

要判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。

JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort());  //true
或者
[1,2,3].sort().toString() === [3,2,1].sort().toString();  //true

经验证,上述方法对复杂数组结构不适用。

JS 判断两个对象是否相同

这是网上某大神封装对比对象是否相同的 function。

    let cmp = ( x, y ) => {
// If both x and y are null or undefined and exactly the same
        if ( x === y ) {
            return true;
        }

// If they are not strictly equal, they both need to be Objects
        if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {
            return false;
        }

//They must have the exact same prototype chain,the closest we can do is
//test the constructor.
        if ( x.constructor !== y.constructor ) {
            return false;
        }

        for ( var p in x ) {
            //Inherited properties were tested using x.constructor === y.constructor
            if ( x.hasOwnProperty( p ) ) {
                // Allows comparing x[ p ] and y[ p ] when set to undefined
                if ( ! y.hasOwnProperty( p ) ) {
                    return false;
                }

                // If they have the same strict value or identity then they are equal
                if ( x[ p ] === y[ p ] ) {
                    continue;
                }

                // Numbers, Strings, Functions, Booleans must be strictly equal
                if ( typeof( x[ p ] ) !== "object" ) {
                    return false;
                }

                // Objects and Arrays must be tested recursively
                if ( ! Object.equals( x[ p ], y[ p ] ) ) {
                    return false;
                }
            }
        }

        for ( p in y ) {
            // allows x[ p ] to be set to undefined
            if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {
                return false;
            }
        }
        return true;
    };

经检测,同样也不支持复杂数据结构的对象。

一般情况下用的话上述2种方法已经够用了,拿来作比较的一般都是简单的数据结构。

 

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值