javascript 令人惊讶的数组比较 [英] javascript surprising array comparison
问题描述
我正在尝试比较 javascript 中的两个数组.
I'm trying to compare two arrays in javascript.
我想要的是:
a
a < b ⇔ ∃ i ≥ 0 s.t. a[i] < b[i] and ∀ 0 ≤ j < i, a[j] = b[j]
因此非负数数组可以按需要工作:
So arrays of non-negative numbers work as desired:
firebug> [0,1,2,3,4] < [1,0,0]
true
并且将负数与零进行比较按预期工作:
And comparing negative numbers with zero works as expected:
firebug> [-1, 1] < [0, 0]
true
但是将负数与负数进行比较是......令人惊讶:
But comparing negative numbers with negative numbers is... suprising:
firebug> [-2] < [-1]
false
firebug> -2 < -1
true
这里发生了什么,所以我可以纠正我对javascript中数组比较意味着的直觉?
What's going on here, so I can correct my intuition for what array comparison means in javascript?
推荐答案
数组转为字符串,归结为.join()
,依次用逗号连接元素(,
) 作为分隔符.
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
因为-
(45)的字符代码小于0
(48)的字符代码).
because the character code of -
(45) is smaller than the character code of 0
(48).
另一方面,
"-2" < "-1" === false
因为比较了第二个字符代码(第一个都是-
,所以还没有给出结果),以及2
的字符代码(50) 比 1
(49) 的字符代码大,因此产生 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.
这篇关于javascript 令人惊讶的数组比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!