表达式
[1, 2, 3] == [1, 2, 3]
评估 Coffeescript 中的false
,但是有一种简洁,惯用的方法来测试数组相等吗?
答案 0 :(得分:14)
如果您正在处理数字数组,并且您知道数组中没有空值或未定义的值,则可以将它们作为字符串进行比较:
a = [1, 2, 3]
b = [1, 2, 3]
console.log "#{a}" is "#{b}" # true
console.log '' + a is '' + b # true
但请注意,一旦开始比较其他不是数字的数组,这将会中断:
a = [1, 2, 3]
b = ['1,2', 3]
console.log "#{a}" is "#{b}" # true
如果您想要更强大的解决方案,可以使用Array#every
:
arrayEqual = (a, b) ->
a.length is b.length and a.every (elem, i) -> elem is b[i]
console.log arrayEqual [1, 2, 3], [1, 2, 3] # true
console.log arrayEqual [1, 2, 3], [1, 2, '3'] # false
console.log arrayEqual [1, 2, 3], ['1,2', 3] # false
请注意,它首先比较数组的长度,以便arrayEqual [1], [1, 2, 3]
不返回true。
答案 1 :(得分:6)
如果你不介意引入Underscore.js依赖关系,你可以使用它的一些实用程序。它并不是非常优雅,但我想不出用简单的coffeescript做更简单的方法:
a = [ 1, 2, 3 ]
b = [ 1, 2, 3 ]
equal = a.length == b.length and _.all( _.zip( a, b ), ([x,y]) -> x is y )
答案 2 :(得分:4)
我不会认为这是惯用的,但这样做可以在不添加额外库的情况下实现:
a = [1, 2, 3, 4]
b = [22, 3, 4]
areEqual = true
maxIndex = Math.max(a.length, b.length)-1
for i in [0..maxIndex]
testEqual = a[i] is b[i]
areEqual = areEqual and testEqual
console.log areEqual
更简洁的方法是使用JavaScript的reduce()函数。这有点短,但我不确定所有浏览器是否支持reduce。
a = [1, 3, 4, 5]
b = [1, 3, 4, 5]
maxIndex = Math.max(a.length, b.length)-1
areEqual = true
[0..maxIndex].reduce (p, c, i, ar) -> areEqual = areEqual and (a[i] is b[i])
console.log "areEqual=#{areEqual}"
答案 3 :(得分:3)
以下效果很好,不需要依赖:
arrayEqual = (ar1, ar2) ->
JSON.stringify(ar1) is JSON.stringify(ar2)
答案 4 :(得分:0)
我是Sugar.js的粉丝。如果您碰巧使用它:
a = [1, 2, 3]
b = [1, 2, 3]
Object.equal(a, b)
答案 5 :(得分:0)
如果数组具有相同的长度且所有具有相同索引的值具有相同的值,则此函数返回true
。如果任一参数不是数组,则抛出错误。
isArray = Array.isArray || (subject) ->
toString.call(subject) is '[object Array]'
compareArrays = (a, b) ->
unless isArray(a) and isArray b
throw new Error '`arraysAreEqual` called with non-array'
return false if a.length isnt b.length
for valueInA, index in a
return false if b[index] isnt valueInA
true