js中判断数组或对象是否相等的方法

一、数组

function ArrayIsEqual(arr1, arr2) {
  if (arr1 === arr2) return true // 指针相同必相等
  if (arr1.length !== arr2.length) return false // 长度不同必不相等
  for (let i in arr1) {
    if (arr1[i] !== arr2[i]) return false // 只要出现一次不相等,两者就不相等
  }
  return true
}
const arr1 = [1,2,3]
const arr2 = [1,2,3,4]
const res = ArrayIsEqual(arr1, arr2)
console.log(res) // false
// 此方式只能验证数组里的值是Number类型
const arr1 = [1,2,3,4]
const arr2 = [2,1,3,4]
const res = JSON.stringify(arr1.sort((a, b) => a - b)) === JSON.stringify(arr2.sort((a, b) => a - b))
console.log(res) // true

// 此方式只能验证数组里的值是String类型
const arr1 = ['Tom','Bob','Jack']
const arr2 = ['Bob','Jack','Tom']
arr1.sort()
arr2.sort()
const res = arr1.toString() === arr2.toString()
console.log(res) // true

二、对象

function ObjectIsEqual(x, y) {    
  if (x === y) return true // 指向同一内存时

  if ((typeof x === "object" && x !== null) && (typeof y === "object" && y !== null)) {
    if (Object.keys(x).length !== Object.keys(y).length) return false
      
    for (let prop in x) {
      if (y.hasOwnProperty(prop)) {
        if (!ObjectIsEqual(x[prop], y[prop])) return false         
      }
      else return false          
    }
    return true
  }
  else return false      
}

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/108881384