欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何判断两个变量的值是否相等

程序员文章站 2022-04-09 20:05:18
...

1.相关代码

 function isObject (obj) {
    return Object.prototype.toString.call({}).slice(8,-1) === 'object'
}
function looseEqual (a, b) {
    if (a === b) return true
    const isObjectA = isObject(a)
    const isObjectB = isObject(b)
    if (isObjectA && isObjectB) {
      try {
        const isArrayA = Array.isArray(a)
        const isArrayB = Array.isArray(b)
        if (isArrayA && isArrayB) {
          return a.length === b.length && a.every((e, i) => {
            return looseEqual(e, b[i])
          })
        } else if (a instanceof Date && b instanceof Date) {
          return a.getTime() === b.getTime()
        } else if (!isArrayA && !isArrayB) {
          const keysA = Object.keys(a)
          const keysB = Object.keys(b)
          return keysA.length === keysB.length && keysA.every(key => {
            return looseEqual(a[key], b[key])
          })
        } else {
          return false
        }
      } catch (e) {
        return false
      }
    } else if (!isObjectA && !isObjectB) {
      return String(a) === String(b)
    } else {
      return false
    }
}
复制代码

2.使用场景

    //定义
    var a = NaN, a1 = NaN
    var b = new Date('2019'), b1 = new Date('2019')
    var c = {name:'jack',age:23}, c1 = {name:'jack',age:23}
    var d = [1,2,3], d1 = [1,2,3]
    
    //使用前
    a === a1 //false
    b === b1 //false
    c === c1 //false
    d === d1 //false
    
    //使用后
    looseEqual (a, a) //true
    looseEqual (b, b1) //true
    looseEqual (c, c1) //true
    looseEqual (d, d1) //true
复制代码