用Javascript和Python比较两个列表的最佳方法是什么?

2024-06-30 15:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我对JavaScript很熟悉,但对python很熟悉。在Python中,我得到以下输出:

In [1]: [1,9,[5,4,2]] > [1,9,[14,5,4]]
Out[1]: False

在JavaScript中:

> [1,9,[5,4,2]] > [1,9,[14,5,4]]
true

在比较之前,数组似乎被转换为字符串。

现在我想自己写一个函数,遍历数组,比较每个元素。 我想出了这个咖啡脚本代码:

compare_list = (a, b)->
    if typeof a == "object" and typeof b != "object"
        return 1
    else if typeof a != "object" and typeof b == "object"
        return -1
    else if typeof a != "object" and typeof b != "object"
        if a > b
            return 1
        else if a < b
            return -1
        else
            return 0
    else if typeof a == "object" and typeof b == "object"
        for i in [0...a.length]
            if i > (b.length-1)
                return 1
            tmp = compare_list a[i], b[i]
            if tmp != 0
                return tmp
        if b.length > a.length
            return -1
        return 0

它以这种方式工作,但是typeof a == "object"部分在我看来不正确。有更简单/更好/更可靠的解决方案吗?

谢谢你的帮助。


Tags: andinfalsereturnifobject数组javascript