// 实现效果
let a = { name: 'zfb', age: 18, major: { main: 'math', other: 'chinese'} }
let b = { name: 'zfb', age: 18, major: { main: 'math', other: 'chinese'} }
console.log(a === b) // false
Under normal circumstances, two objects cannot be equal, although the key and value are the same, because they have different memory pointers, the isEqual function is implemented
var result = isEqual(a, b)
console.log(result) // true
Code:
Pre-knowledge: Object.keys()
If the object is passed in, return the key array of the object; if the passed in is an array, return the index subscript array
let c = { name: 'zfb', age: 18, major: { main: 'math', other: 'chinese'} }
console.log(Object.keys(c)) // ["name", "age", "major"]
let arr = ['1', '2', '3']
console.log(Object.keys(arr)) // ["0", "1", "2"]
Code:
// 判断是否是对象或者数组
function isObject(obj) {
return typeof obj === 'object' && obj !== null
}
function isEqual (obj1, obj2) {
// 参数有一个不是对象 直接判断值是否相等就行
if (!isObject(obj1) || !isObject(obj2)) {
return obj1 === obj2
}
// 如果两个数都是数组或者对象
// 1. 先比较keys的个数,如果个数不相同 直接就不想等了
var obj1Keys = Object.keys(obj1)
var obj2Keys = Object.keys(obj2)
if (obj1Keys.length !== obj2Keys.length) {
return false
}
// 如果个数相同再以obj1为基准 和 obj2依次递归比较
// for...in 适用于对象,也适用于数组
for (let key in obj1) {
const res = arguments.callee(obj1[key], obj2[key]) // 递归
if (!res) {
return false
}
}
return true
}
Suitable for arrays and objects