思路:(这里只做了对象中如果有多层,多层嵌套还是个对象的形式)
1.把两个对象用Object.entries()转成数组,循环这两个数组,判断key和value,value再去判断数据类型(如果还是一个对象,那就用递归去重复),直到是基本数据类型的val1 == val2
2.通过一个中间变量去存储布尔类型值,在循环判断中,满足条件就设置true,否则就为false。最后再return出去这个变量,如果是true,就证明两个对象相等
var obj1 = { name: 'zs', age: 18, hobby: { eat: 'apple', drink: { a: 'colo', b: 'mink' } } } var obj2 = { name: 'zs', age: 18, hobby: { eat: 'apple', drink: { a: 'colo', b: 'mink' } } } // var x = { // eat: 'apple' // } // var y = { // eat: 'apple' // } // console.log(x === y, "相等吗"); 两个对象是两个堆内存,当然不相等 //false function isEqual(a, b) { let flag = true; (function fn(a, b) { let arr1 = Object.entries(a); let arr2 = Object.entries(b); for (let [key, val] of arr1) { for (let [key2, val2] of arr2) { if (key === key2) { if (val === val2) { // console.log('我是相等那个', key, val); flag = true } else { flag = false if (val instanceof Object && val2 instanceof Object) { fn(val, val2) } } } else { flag = false } } } })(a, b) return flag; } let res = isEqual(obj1, obj2); console.log(res);