在比较JavaScript中的字符串时,为什么一个字符串比另一个字符串大?

时间:2022-11-23 22:50:44

I see this code from a book:

我从一本书中看到了这段代码:

var a = "one";
var b = "four";
a>b; // will return true

but it doesn't mention why "one" is bigger than "four". I tried c = "a" and it is smaller than a and b. I want to know how JavaScript compares these strings.

但它没有提到为什么“一个”大于“四个”。我试过c =“a”,它小于a和b。我想知道JavaScript如何比较这些字符串。

3 个解决方案

#1


33  

Because, as in many programming languages, strings are compared lexicographically.

因为,在许多编程语言中,字符串按字典顺序进行比较。

You can think of this as a fancier version of alphabetical ordering, the difference being that alphabetic ordering only covers the 26 characters a through z.

您可以将此视为字母排序的更高级版本,不同之处在于字母排序仅涵盖26个字符a到z。


This answer is in response to a question, but the logic is exactly the same. Another good one: String Compare "Logic".

这个答案是对java问题的回应,但逻辑完全相同。另一个好的:字符串比较“逻辑”。

#2


7  

"one" starts with 'o', "four" starts with 'f', 'o' is later in the alphabet than 'f' so "one" is greater than "four". See this page for some nice examples of JavaScript string comparisons (with explanations!).

“一个”以“o”开头,“四个”以“f”开头,“o”在字母表后面比“f”更长,因此“一个”大于“四”。有关JavaScript字符串比较的一些很好的示例,请参阅此页面(有解释!)。

#3


3  

Javascript uses Lexicographical order for the > operator. 'f' proceeds 'o' so the comparison "one" > "four" returns true

Javascript使用>操作符的词典顺序。 'f'继续'o',因此比较“one”>“four”返回true

#1


33  

Because, as in many programming languages, strings are compared lexicographically.

因为,在许多编程语言中,字符串按字典顺序进行比较。

You can think of this as a fancier version of alphabetical ordering, the difference being that alphabetic ordering only covers the 26 characters a through z.

您可以将此视为字母排序的更高级版本,不同之处在于字母排序仅涵盖26个字符a到z。


This answer is in response to a question, but the logic is exactly the same. Another good one: String Compare "Logic".

这个答案是对java问题的回应,但逻辑完全相同。另一个好的:字符串比较“逻辑”。

#2


7  

"one" starts with 'o', "four" starts with 'f', 'o' is later in the alphabet than 'f' so "one" is greater than "four". See this page for some nice examples of JavaScript string comparisons (with explanations!).

“一个”以“o”开头,“四个”以“f”开头,“o”在字母表后面比“f”更长,因此“一个”大于“四”。有关JavaScript字符串比较的一些很好的示例,请参阅此页面(有解释!)。

#3


3  

Javascript uses Lexicographical order for the > operator. 'f' proceeds 'o' so the comparison "one" > "four" returns true

Javascript使用>操作符的词典顺序。 'f'继续'o',因此比较“one”>“four”返回true