在 JavaScript 中比较字符串时,为什么一个字符串大于另一个? [英] Why is one string greater than the other when comparing strings in JavaScript?
问题描述
我从一本书中看到这段代码:
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.
您可以将其视为 字母顺序 的更高级版本,区别在于字母顺序仅涵盖 a
到 z
的 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 问题,但是逻辑完全一样.另一个不错的:字符串比较逻辑".
This answer is in response to a java question, but the logic is exactly the same. Another good one: String Compare "Logic".
这篇关于在 JavaScript 中比较字符串时,为什么一个字符串大于另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!