Javascript 为什么字符串“11”小于字符串“3”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10863092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:17:42  来源:igfitidea点击:

Why is string "11" less than string "3"?

javascriptstringcomparison

提问by jilseego

if ('11' < '3') alert('true');

It's obvious that it's not comparing them by length but by encoding instead. However, I don't understand how it works. I need some explanation :-)

很明显,它不是通过长度来比较它们,而是通过编码来比较它们。但是,我不明白它是如何工作的。我需要一些解释:-)

回答by Quentin

Strings are compared lexicographicaly. i.e. character by character until they are not equal or there aren't any characters left to compare. The first character of '11' is less than the first character of '3'.

字符串按字典顺序进行比较。即逐个字符,直到它们不相等或没有任何字符可供比较。“11”的第一个字符小于“3”的第一个字符。

> '11' < '3'
true
> '31' < '3'
false
> '31' < '32'
true
> '31' < '30'
false

If we use letters then, since bis not less than a, abcis not less than aaa, but since cis less than d, abcis less than abd.

如果我们使用字母,那么因为b不小于aabc不小于aaa,但是因为c小于dabc小于abd

> 'abc' < 'aaa'
false
> 'abc' < 'abd'
true

You can explicitly convert strings to numbers:

您可以显式地将字符串转换为数字:

> +'11' < '3'
false

回答by Ja?ck

By default, JavaScript will compare two strings by each character's ordinal value; much like how strcmp()works in C.

默认情况下,JavaScript 会根据每个字符的序数值比较两个字符串;就像strcmp()在 C 中的工作方式一样。

To make your comparison work, you can cast either side to a number to tell the interpreter your intentions of numeric comparison:

为了使您的比较有效,您可以将任一侧转换为一个数字,以告诉解释器您进行数字比较的意图:

Number('11') < '3' // false
+'11' < '3' // false, using + to coerce '11' to a numeric

'11' < Number('3') // false
'11' < +'3' // false

回答by Ramesh Kotha

In Many Programming languages Strings are compared as lexicographically. You can check Alphabetical order

在许多编程语言中,字符串按字典顺序进行比较。您可以检查字母顺序

回答by Sarfraz

It compares by each character, the following will be false:

它按每个字符进行比较,以下将是false

if ('41' < '3') alert('true');

Since 4is not less than 3. So essentially your comparison boiled down to this:

由于4不小于3. 所以基本上你的比较归结为:

if ('1' < '3') alert('true'); // true

回答by ThiefMaster

'1' < '3'and since the first character is the "most significant character" (not that this term makes any sense). Any following characters will not be compared anymore.

'1' < '3'并且因为第一个字符是“最重要的字符”(不是这个术语有任何意义)。将不再比较任何以下字符。

回答by Rajasekhar

It has been treated as string comparision. So 1 < 3 (1st chars of two strings) then string 11 preceeds string 3

它已被视为字符串比较。所以 1 < 3(两个字符串的第一个字符)然后字符串 11 在字符串 3 之前