javascript 令人惊讶的数组比较
我正在尝试比较 javascript 中的两个数组。
我想要的是:
a < b ⇔ ∃ i ≥ 0 st a[i] < b[i] 且 ∀ 0 ≤ j <我,a[j] = b[j]
所以非负数数组可以按预期工作:
firebug> [0,1,2,3,4] < [1,0,0]
true
将负数与零进行比较可以按预期工作:
firebug> [-1, 1] < [0, 0]
true
但是将负数与负数进行比较......令人惊讶:
firebug> [-2] < [-1]
false
firebug> -2 < -1
true
这里发生了什么,所以我可以纠正我对 JavaScript 中数组比较意味着的直觉?
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 < 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
What's going on here, so I can correct my intuition for what array comparison means in javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该数组被转换为字符串,最终转化为
.join()
,后者用逗号 (,
) 作为分隔符连接元素。因为
-
(45) 的字符代码小于0
(48) 的字符代码。另一方面,
因为比较了第二个字符代码(第一个都是
-
,所以还没有给出结果),并且2
的字符代码(50) 比1
(49) 的字符代码大,因此结果为false
。它归结为字典排序(即按字符代码)而不是数字排序,即使元素是数字(因为字符串强制)。
基本上不建议比较数组。它被隐式定义为字符串比较,但这可能会产生令人惊讶的结果。
The array is converted to a string, which comes down to
.join()
, which in turn joins the elements with a comma (,
) as delimiter.because the character code of
-
(45) is smaller than the character code of0
(48).On the other hand,
because the second character codes are compared (the first are both
-
, so that doesn't give a result yet), and the character code for2
(50) is bigger than the character code of1
(49), so this yieldsfalse
.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 数组比较之类的东西。
在所有情况下发生的情况是,您的数组首先通过将其内容连接在一起而转换为字符串。因此,字符串“-2”不小于字符串“-1”,因为在字符集中字符“2”位于“1”之后。同样,“-1,1”小于“0,0”,因为“-”字符位于数字之前。
您可以亲眼看到,在所有情况下您的比较:
得到与以下完全相同的结果:
或:
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:
get exactly the same results as:
or:
我找不到关于如何在 Javascript 中实际比较数组并获得“预期”结果的答案,所以这里是代码
I couldn't find an answer about how to actually compare arrays in Javascript and get "expected" results, so here is the code