javascript 对象的比较是比较坑爹的一件事,因为javascript对象比较的是引用地址!当两个内容完全一样的对象比较:
var object1={ name:"1234 ", code:123, test:"321", }; var object2={ name:"1234 ", code:123, test:"321", }; console.log(object1==object2) //false
解决方法使用hashcode
javascript hashcode实现
function hashcode(str) { 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; }
实例:
var object1={ name:"1234 ", code:123, test:"321", }; var object2={ name:"1234 ", code:123, test:"321", }; console.log(object1==object2) //false var test1=hashcode(JSON.stringify(object1)); var test2=hashcode(JSON.stringify(object2)); console.log(test1,test2,test1==test2);