arrays - 有没有一种惯用的方法来测试Coffeescript中的数组相等性?

标签 arrays coffeescript equality

表达方式

[1, 2, 3] == [1, 2, 3]

在Coffeescript中评估为false,但是有一种简洁,惯用的方法来测试数组是否相等?

最佳答案

如果要处理数字数组,并且知道数组中没有空值或未定义的值,则可以将它们作为字符串进行比较:

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。

关于arrays - 有没有一种惯用的方法来测试Coffeescript中的数组相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11142666/

相关文章:

javascript - 对对象数组进行数组搜索 - Javascript

node.js - 我可以直接从 node.js 运行 .coffee 文件吗?

reactjs - react : get element attribute from method

java - 如何在 Java 中比较字符串?

php - 按用户 ID 和 photo_id 列出的下一张/上一张图像

c - 从指针数组中存储/获取值

c - 如何对结构的二维动态数组进行排序

javascript - 禅编码 : ability to ascend the DOM tree using ^

python 集合包含与列表包含

C++ 比较指向 NULL 的指针