JavaScript的奇阵比较 [英] javascript surprising array comparison

查看:125
本文介绍了JavaScript的奇阵比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想两个数组在JavaScript中进行比较。

I'm trying to compare two arrays in javascript.

我想的是:

A< B⇔ &存在; I≥ 0 S.T。一[1] - ; B〔i]和∀ 0乐; J<我,一个[J] = B [J]

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?

推荐答案

该数组转换为字符串,这归结为。加入(),这又加入的元素用逗号()作为分隔符。

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

因为字符code 的的 - (45)比的字符code较小 0 (48)。

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

在另一方面,

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

由于第二个字符codeS进行比较(第一均 - ,这样不给结果还),字符code表示 2 (50)的的比 1 的字符code (49),所以这个收益率

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.

它归结为一个lexographical排序(即由字符codeS),而不是一个算一个,即使元素是数字(因为字符串胁迫)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆