首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JavaScript中对字符串进行排序

如何在JavaScript中对字符串进行排序
EN

Stack Overflow用户
提问于 2008-09-09 11:25:15
回答 16查看 477.5K关注 0票数 443

我有一个对象列表,希望根据string类型的字段attr进行排序。我试着使用-

代码语言:javascript
复制
list.sort(function (a, b) {
    return a.attr - b.attr
})

但是发现在JavaScript中-似乎不能处理字符串。如何根据类型为string的属性对对象列表进行排序?

EN

Stack Overflow用户

发布于 2013-02-08 02:06:20

我已经为这个问题困扰了很长时间,所以我最终研究了这个问题,并给出了这个冗长的理由来解释为什么事情是这样的。

spec

代码语言:javascript
复制
Section 11.9.4   The Strict Equals Operator ( === )

The production EqualityExpression : EqualityExpression === RelationalExpression
is evaluated as follows: 
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison 
  rval === lval. (See 11.9.6)

现在我们转到11.9.6

代码语言:javascript
复制
11.9.6   The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. 
Such a comparison is performed as follows: 
- If Type(x) is different from Type(y), return false.
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is Number, then
...
- If Type(x) is String, then return true if x and y are exactly the 
  same sequence of characters (same length and same characters in 
  corresponding positions); otherwise, return false.

就这样。如果参数是完全相同的字符串(相同的长度和相应位置的相同字符),则应用于字符串的三重等于运算符返回true。

因此,当我们试图比较可能来自不同来源的字符串,但我们知道它们最终将具有相同的值时,===将会起作用-这对于代码中的内联字符串来说是一个足够常见的场景。例如,如果我们有一个名为connection_state的变量,并且我们希望知道它现在处于以下哪一种状态,我们可以直接使用===

但还有更多。在11.9.4上方,有一条简短的说明:

代码语言:javascript
复制
NOTE 4     
  Comparison of Strings uses a simple equality test on sequences of code 
  unit values. There is no attempt to use the more complex, semantically oriented
  definitions of character or string equality and collating order defined in the 
  Unicode specification. Therefore Strings values that are canonically equal
  according to the Unicode standard could test as unequal. In effect this 
  algorithm assumes that both Strings are already in normalized form.

嗯。现在怎么办?从外部获得的字符串可能是奇怪的独一码,而我们温和的===不能很好地处理它们。localeCompare应运而生:

代码语言:javascript
复制
15.5.4.9   String.prototype.localeCompare (that)
    ...
    The actual return values are implementation-defined to permit implementers 
    to encode additional information in the value, but the function is required 
    to define a total ordering on all Strings and to return 0 when comparing
    Strings that are considered canonically equivalent by the Unicode standard. 

我们现在可以回家了。

tl;dr;

要比较javascript中的字符串,请使用localeCompare;如果您知道字符串没有非ASCII码组件,因为它们是内部程序常量,那么===也可以工作。

票数 7
EN
查看全部 16 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档