源代碼code
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))