js判断两个对象是否相等


const isEqualTwoObjects = (firstObj, secondObj) => {
  // 0. 如果这两个对象指向同一个引用
  if (firstObj === secondObj) {
    return true
  }
  // 1. 第一步拿到这两个对象的 键
  const firstObjKeys = Object.getOwnPropertyNames(firstObj)
  const secondObjKeys = Object.getOwnPropertyNames(secondObj)
  // 2. 判断键 长度是否一致
  if (firstObjKeys.length !== secondObjKeys.length) {
    return false
  }
  // 3. 判断 键名 是否相同
  const set = new Set(firstObjKeys)
  const bool = secondObjKeys.every(item => set.has(item))
  if (!bool) {
    return false
  }

  const getType = value => {
    const result = Object.prototype.toString.call(value).split(' ')
    const str = result[1]
    const len = str.length
    const type = str.substring(0, len - 1).toLowerCase()
    return type
  }

  // 4. 进行比较判断每个属性的值是否相等
  for (let i = 0; i < firstObjKeys.length; i++) {
    const item = firstObjKeys[i]
    const firstObjValue = firstObj[item]
    const secondObjValue = secondObj[item]
    const firstObjValueType = getType(firstObjValue)
    const secondObjValueType = getType(secondObjValue)
    if (firstObjValueType !== secondObjValueType) {
      return false
    }
    if (firstObjValueType === 'function' || firstObjValueType === 'array') {
      if (firstObjValue.toString() !== secondObjValue.toString()) {
        return false
      }
    } else if (firstObjValueType === 'object') {
      if (!isEqualTwoObjects(firstObjValue, secondObjValue)) {
        return false
      }
    } else if (firstObjValue !== secondObjValue) {
      return false
    }
  }
  return true
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值