首页 > 关于javascript里判断数组内对象是否相等的问题?

关于javascript里判断数组内对象是否相等的问题?

现在有数组arr1,里面存都是对象:

var arr1 = [{name:"haha1"},{name:"haha2"}];

如果有变量a1,

var a1 = {name:"haha1"};

那么,我如何判断a1与arr1里的相关对象相等呢?(对象是引用类型一般类型的"=="是无法判断吧)


题主是想得到全等的答案么?

var a1 = { a: 1 };
var a2 = { a: 1 };
a1 === a2 // 可能全等吗?

对象的比较方法应该要清楚,因为对象比较的是原型的相同与否,这段代码给你参考
Object.equals = function( 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;
};


arr1.forEach(function(v,i){
    if(JSON.stringify(v) == JSON.stringify(a1)) {
        console.log(JSON.stringify(a1));//{"name":"haha1"}
        }
})

自己定义比较的规则

function findIndexOf(obj,array,compareFn){
    //在此假设传入的参数都符合预期,不做类型判断
    var result;
    compareFn= compareFn||function(itemA,itemB){
        return itemA==itemB;
    };
    for(var i=0;i<array.length;i++){
        if(compareFn.call(null,array[i], obj)){
            result={
                index:i,
                value:array[i]
            };
            break;
        }
    }
    
    return result||{
          index:-1
    };
    
}

var arr1 = [{name:"haha1"},{name:"haha2"}];
var a1 = {name:"haha1"};

//自己定义比较规则
var result=findIndexOf(a1,arr1,function(itemA,itemB){
    return itemA.name===itemB.name;
});
//找到,输出>=0,并且能从result中获取和a1匹配的arr中的对象;没找到,输出-1
console.log(result.index);
【热门文章】
【热门文章】