Javascript实现hashcode函数实现对象比较与原理说明
作者:ztnhnr
在JavaScript中,数值的比较是比较简单的,使用相等(==)和全等(===)符号基本上可以解决大多数非对象的比较。但是相等(==)和全等(===)符号在对象 object 的比较上,就不能满足所有的要求了
在JavaScript中,数值的比较是比较简单的,使用相等(==)和全等(===)符号基本上可以解决大多数非对象的比较。但是相等(==)和全等(===)符号在对象 object 的比较上,就不能满足所有的要求了,hashCode是用于查找使用的,而equals是用于比较两个对象是否相等的
如下面的代码:
// 定义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。
javascript中获得HashCode值
直接使用这三个方法即可:
function hashCode(strKey)
{
var hash = 0;
if(!isNull(strKey))
{
for (var i = 0; i < strKey.length; i++)
{
hash = hash * 31 + strKey.charCodeAt(i);
hash = intValue(hash);
}
}
return hash;
}
function isNull(str){
return str == null || str.value == "";
}
function intValue(num)
{
var MAX_VALUE = 0x7fffffff;
var MIN_VALUE = -0x80000000;
if(num > MAX_VALUE || num < MIN_VALUE)
{
return num &= 0xFFFFFFFF;
}
return num;
}脚本之家小编推荐一个不错的写法
String.prototype.hashCode = function() {
for (var a = 31,b = 0,c = this.length; b < c;)
a ^= (a << 5) + (a >> 2) + this.charCodeAt(b++);
return a
};到此这篇关于Javascript实现hashcode函数实现对象比较与原理说明的文章就介绍到这了,更多相关Javascript hashcode内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
