javascript surprising array comparison

前端 未结 3 863
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 21:27

I\'m trying to compare two arrays in javascript.

What I\'d like is:

a < b ⇔ ∃ i ≥ 0 s.t. a[i] < b[i] and ∀ 0 ≤ j

3条回答
  •  隐瞒了意图╮
    2020-11-27 21:53

    There's no such thing as JavaScript array comparison in any form similar to what you describe.

    What's happening in all cases is that your arrays are being converted first to strings by joining their contents together. Thus, the string "-2" is not less than the string "-1", because the character "2" comes after "1" in the character set. Similarly, "-1,1" is less than "0,0" because the "-" character comes before the digits.

    You can see for yourself that in all cases your comparisons:

    array1 < array2
    

    get exactly the same results as:

    ("" + array1) < ("" + array2)
    

    or:

    array1.join(",") < array2.join(",")
    

提交回复
热议问题