Javascript实现 hashcode 函数实现对象比较

在JavaScript中,数值的比较是比较简单的,使用相等(==)和全等(===)符号基本上可以解决大多数非对象的比较。但是相等(==)和全等(===)符号在对象 object 的比较上,就不能满足所有的要求了,如下面的代码:

// 定义2个属性值完全相同的实例对象
var obj1 = {
    name: "neil",
    age: 100
};

var obj2 = {
    name: "neil",
    age: 100
};

var obj3 = obj2;

console.log(obj1 == obj2)   // false
console.log(obj2 == obj3)   // true
console.log(obj2 === obj3)   // true

    从上面的代码中可以看出,对象 obj1 和 obj2 是不等的,但是 obj2 和 obj3 是相等的。这是因为在比较对象的时候,比较的是对象的地址,只有两个对象的引用地址指向同一个地址时,对象才相等。

    但有时,我们希望如果两个对象的内容完全一样时(即使引用的不是同一个对象),就判断两个对象相等。如果需要判断两个对象在字面意义上相等,可以使用类似Java中的 hashcode 方法来实现

// 定义hashcode函数
function hashcode(obj) {
    // 将对象obj转换为字符串
    var str = JSON.stringify(obj);
    
    var hash = 0, i, chr, len;
    if (str.length === 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
        chr = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

    注意:计算使用的是字符串,因此先将参数 obj 转换为字符串

    通过以上方法,我们可以计算两个对象的hashcode,然后再进行比较:   

// 定义2个属性值完全相同的实例对象
var obj1 = {
    name: "neil",
    age: 100
};

var obj2 = {
    name: "neil",
    age: 100
};

// 定义hashcode函数
function hashcode(obj) {
    var str = JSON.stringify(obj);
    var hash = 0, i, chr, len;
    if (str.length === 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
        chr = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

console.log(hashcode(obj1)); // -311732675
console.log(hashcode(obj2)); // -311732675
console.log(obj1 == obj2); // false
console.log(hashcode(obj1) == hashcode(obj2)); // true

    以上代码,对应 obj1 和 obj2,hashcode方法都输出同一个值:-311732675。因此再比较两个对象的hashcode值时,返回 true。

猜你喜欢

转载自blog.csdn.net/ztnhnr/article/details/107731965
今日推荐