一、使用Object.getOwnPropertyNames()
该方法和Object.keys()功能一样,不同的地方在于Object.getOwnPropertyNames返回对象本身全部的属性,而Object.keys返回对象自身的(不含继承的)所有可枚举属性(不含Symbol属性)(即返回enumerable为false的属性)
共同点是俩者都不会返回自身原型链上的属性。
JavaScript代码
- var obj = {"name":"liuxinxiu","age":18,"info":"1234"}
- var obj2 = obj;
- var obj3 = {"name":"liuxinxiu","age":18,"info":"123"}
- function checkInfo(obj1, obj2){
- //判断是否指向同一内存
- if (obj1 === obj2) return true;
- let bankInfo = Object.getOwnPropertyNames(obj1),
- oldBankInfo = Object.getOwnPropertyNames(obj2)
- //判断长度不相同直接返回不同
- if(bankInfo.length !== oldBankInfo.length) return false
- for(let i=0,max=bankInfo.length; i<max; i++){
- let prop_name = bankInfo[i]
- if(obj1[prop_name] !== obj2[prop_name]){
- return false
- }
- }
- return true
- }
- console.log(checkInfo(obj,obj3))
二、使用Object.keys()或者Object.entries().toString()
Object.keys()是将对象中键先取出来组成数组,然后先比较键。而后通过键在比较值
Object.entries()是将键和值分别组成俩个数组。然后使用toString将键值数组转化为字符串去比较
JavaScript代码
- checkInfo() {
- // object.keys
- let bankInfo = Object.keys(this.params.bankInfo),
- oldBankInfo = Object.keys(this.params.oldBankInfo)
- if (oldBankInfo.length !== bankInfo.length) return false
- for (let i = 0; i <= bankInfo.length - 1; i++) {
- let key = bankInfo[i];
- if (!oldBankInfo.includes(key)){
- return false
- }
- if (this.params.oldBankInfo[key] !== this.params.bankInfo[key]){
- return false
- }
- }
- // object.entries
- console.log(Object.entries(this.params.bankInfo).toString() === Object.entries(this.params.oldBankInfo).toString()) //true
- console.log(Object.entries(this.params.bankInfo).toString()) //accountType,2,nationality,CHN,bankName,,bankCode,
- console.log(Object.entries(this.params.oldBankInfo).toString()) //accountType,2,nationality,CHN,bankName,,bankCode,
- }
三、使用JSON.stringify()或。适用于俩个对象属性顺序相同
JavaScript代码
- let bankInfo = {
- accountType : 2,
- nationality:'CHN', //国籍
- bankName : '', //银行名称
- bankCode : '', //银行code
- }
- let oldBankInfo = {
- accountType : 2,
- nationality:'CHN', //国籍
- bankName : '', //银行名称
- bankCode : '', //银行code
- }
- let flag2 = JSON.stringify(bankInfo) == JSON.stringify(oldBankInfo)
- console.log(flag2)