我有一个对象列表,希望根据string类型的字段attr进行排序。我试着使用-
list.sort(function (a, b) {
return a.attr - b.attr
})但是发现在JavaScript中-似乎不能处理字符串。如何根据类型为string的属性对对象列表进行排序?
发布于 2013-02-08 02:06:20
我已经为这个问题困扰了很长时间,所以我最终研究了这个问题,并给出了这个冗长的理由来解释为什么事情是这样的。
从spec
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
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上方,有一条简短的说明:
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应运而生:
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码组件,因为它们是内部程序常量,那么===也可以工作。
https://stackoverflow.com/questions/51165
复制相似问题