按字母顺序比较2个字符串以进行排序 [英] comparing 2 strings alphabetically for sorting purposes

查看:192
本文介绍了按字母顺序比较2个字符串以进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母顺序比较2个字符串以进行排序。例如,我想要一个布尔检查,如 if('aaaa'<'ab')。我试过了,但它没有给我正确的结果,所以我猜这不是正确的语法。如何在jquery或Javascript中执行此操作?

I'm trying to compare 2 strings alphabetically for sorting purposes. For example I want to have a boolean check like if('aaaa' < 'ab'). I tried it, but it's not giving me correct results, so I guess that's not the right syntax. How do I do this in jquery or Javascript?

推荐答案

让我们看一些测试用例 - 尝试在JS中运行以下表达式控制台:

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

全部返回true。

JavaScript逐个字符地比较字符串,字母表中的a出现在b之前 - 因此小于。

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

在你的情况下它的工作原理如下 -

In your case it works like so -


1。 a aaa< a b

1 . "a​aaa" < "​a​b"

比较前两个a字符 - 全部相等,让我们移动到下一个字符。

compares the first two "a" characters - all equal, lets move to the next character.


2。 a a aa< a b

2 . "a​a​​aa" < "a​b​​"

将第二个字符a与b进行比较 - 呐喊! a出现在b之前。返回true。

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

这篇关于按字母顺序比较2个字符串以进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆