coffeeisEqual = (a, b) -> eq(a, b, [], [])
eq = (a, b, aStack, bStack) ->
return a isnt 0 or 1 / a is 1 / b if a is b
return false if a is null and b is undefined
return false if a is undefined and b is null
className = toString.call(a)
return false if className isnt toString.call(b)
switch className
when "[object RegExp]" then return "" + a is "" + b
when "[object String]" then return "" + a is "" + b
when "[object Number]"
return +b isnt +b if +a isnt +a
return if +a is 0 then 1 / +a is 1 / b else +a is +b
when "[object Date]" then return +a is +b
when "[object Boolean]" then return +a is +b
areArrays = className is "[object Array]"
if not areArrays
return false if typeof a isnt "object" or typeof b isnt "object"
aCtor = a.constructor
bCtor = b.constructor
return false if (aCtor isnt bCtor) and not (Utils.isFunction(aCtor) and aCtor instanceof aCtor and Utils.isFunction(bCtor) and bCtor instanceof bCtor) and ("constructor" of a and "constructor" of b)
length = aStack.length
while length--
return bStack[length] is b if aStack[length] is a
aStack.push(a)
bStack.push(b)
if areArrays
size = a.length
result = size is b.length
if result
while size--
break if not (result = eq(a[size], b[size], aStack, bStack))
else
keys = Utils.keys(a)
size = keys.length
result = Utils.keys(b).length is size
if result
while size--
key = keys[size]
break if not (result = Utils.has(b, key) and eq(a[key], b[key], aStack, bStack))
aStack.pop()
bStack.pop()
return result
其实这个事情还真的不太简单的,可以看一下 underscore.js 的是如何实现的:
https://github.com/jashkenas/underscore/blob/master/underscore.js#L111...
事实上你可以看到它的代码非常复杂。
当然用起来是非常简单的,文档在这里:
http://underscorejs.org/#isEqual
所以对于楼主的问题,答案就是没有简单的办法比较,除非用别人写好的,underscore.js 有一万多 star,值得信赖。
两个对象都JSON.stringify 然后进行字符串比较
对underscore中的相等判断我写过一篇文章,你可以参考一下:https://github.com/classicemi/blog/issues/7
用 objA == objB 啊,或者 objA === objB 也行,都返回false;
传送门: https://github.com/wh1100717/localDB/blob/develop/src/core/utils.coffe...
简单的办法就是 JSON.stringify(obj_a) === JSON.stringify(obj_b);
但是注意 1) obj_a(b)中不能有环。
2) 性能比较差