js中比较两个对象是否相同的方法示例
人气:0本文实例讲述了js中比较两个对象是否相同的方法。分享给大家供大家参考,具体如下:
js中,很轻易就可以比较2个普通字符串/数字是否相同,但是,如何比较2个对象是否相同呢?
在此我便给出较为简单的方法,如下:
//比较2个对象是否相同 function isObjEqual(o1,o2){ var props1 = Object.getOwnPropertyNames(o1); var props2 = Object.getOwnPropertyNames(o2); if (props1.length != props2.length) { return false; } for (var i = 0,max = props1.length; i < max; i++) { var propName = props1[i]; if (o1[propName] !== o2[propName]) { return false; } } return true; } var obj1 = {id:1,name:"张三"} var obj2 = {id:2,name:"李四"} var obj3 = {id:1,name:"张三",age:25} var obj4 = {id:1,name:"张三"} console.log(isObjEqual(obj1,obj2));//false console.log(isObjEqual(obj1,obj3));//false console.log(isObjEqual(obj1,obj4));//true
运行结果:
扩展写法:
Object.prototype.vequal = function(obj){ var props1 = Object.getOwnPropertyNames(this); var props2 = Object.getOwnPropertyNames(obj); if (props1.length != props2.length) { return false; } for (var i = 0,max = props1.length; i < max; i++) { var propName = props1[i]; if (this[propName] !== obj[propName]) { return false; } } return true; } var obj1 = {id:1,name:"张三"} var obj2 = {id:2,name:"李四"} var obj3 = {id:1,name:"张三",age:25} var obj4 = {id:1,name:"张三"} console.log(obj1.equal(obj2));//false console.log(obj1.equal(obj3));//false console.log(obj1.equal(obj4));//true
希望本文所述对大家JavaScript程序设计有所帮助。
您可能感兴趣的文章:
加载全部内容