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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7087811/
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 00:47:49  来源:igfitidea点击:

Why is one string greater than the other when comparing strings in JavaScript?

javascriptstringcompare

提问by patriot7

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 如何比较这些字符串。

采纳答案by Matt Ball

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 athrough z.

您可以将其视为字母排序的更高级版本,不同之处在于字母排序仅涵盖 26 个字符az.



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

这个答案是对一个java问题的回应,但逻辑是完全一样的。另一个好方法:String Compare "Logic"

回答by Paul

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

“one”以“o”开头,“four”以“f”开头,“o”在字母表中比“f”晚,因此“one”大于“four”。有关JavaScript 字符串比较的一些不错示例,请参阅此页面(附有解释!)。

回答by martin

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

Javascript 对>运算符使用字典顺序。'f' 继续 'o' 所以比较"one" > "four"返回true