判断两个对象的值是否相等

源代码

function isEqual (a, b) {

const classNameA = toString.call(a)

const classNameB = toString.call(b)

// 如果数据类型不相等,则返回false

if (classNameA !== classNameB) {

return false

} else {

// 如果数据类型相等,再根据不同数据类型分别判断

if (classNameA === '[object Object]') {

for (let key in a) {

if (!isEqual(a[key], b[key])) return false

}

for (let key in b) {

if (!isEqual(a[key], b[key])) return false

}

return true

} else if (classNameA === '[object Array]') {

if (a.length !== b.length) {

return false

} else {

for (let i = 0, len = a.length; i < len; i++) {

if (!isEqual(a[i], b[i])) return false

}

return true

}

} else if (classNameA === '[object Function]') {

return a.toString() === b.toString()

} else {

return Object.is(a, b)

}

}

}

样例

const a = {

arr: [1, true, {a: 6, arr: [9, 0, 6, [5, 9]]}],

d: 0,

obj: { d: 9, arr: [5000]},

e: ()=>{},

f: [0]

}

const b = {

arr: [1, true, {a: 6, arr: [9, 0, 6, [5, 9]]}],

d: 0,

obj: { d: 9, arr: [5000]},

e: ()=>{},

f: [0]

}

console.log(isEqual(a, b))

Logo

前往低代码交流专区

更多推荐