gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:25:18 25 4
gpt4 key购买 nike

表达方式

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com