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

2022-01-25 00:00:00 string compare javascript java

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

I see this code from a book:

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

但它没有提到为什么一"大于四".我试过 c = "a" 并且它小于 a 和 b.我想知道 JavaScript 如何比较这些字符串.

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.

推荐答案

因为在许多编程语言中,字符串是比较的 按字典顺序.

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

您可以将其视为字母顺序的更高级版本,区别在于该字母顺序仅涵盖 az 的 26 个字符.

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.

这个答案是对java 问题,但逻辑完全一样.另一个不错的:字符串比较Logic".

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

相关文章