javascript surprising array comparison

前端 未结 3 860
伪装坚强ぢ
伪装坚强ぢ 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 22:06

    The array is converted to a string, which comes down to .join(), which in turn joins the elements with a comma (,) as delimiter.

    "-1,1" < "0,0" === true
    

    because the character code of - (45) is smaller than the character code of 0 (48).

    On the other hand,

    "-2" < "-1" === false
    

    because the second character codes are compared (the first are both -, so that doesn't give a result yet), and the character code for 2 (50) is bigger than the character code of 1 (49), so this yields false.

    It comes down to a lexographical sorting (i.e. by character codes) and not a numerical one, even if the elements are numbers (because of the string coercion).

    Basically comparing arrays is not recommended. It is implicitly defined as string comparison, but this can yield surprising results.

提交回复
热议问题