我需要对一个数组进行排序,但它只能在 Chrome 中正常工作。在 mozilla 规范中我找到了这段文字,但仍然无法解决这个问题:
"The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y."
和这个链接https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort也许它会对你和我有所帮助
这是我的代码
arr.sort(sortTrip);
function sortTrip(a, b) {
if (a.to != b.from) return 1;
if (a.to == b.from) return -1;
}
这是arr
:
var arr = [
{
"from": "Moscow",
"to": "Rome",
"transport": "NSB Regiontog Train",
"seat": "25"
},
{
"from": "Oslo",
"to": "Paris",
"transport": "NSB Regiontog Train",
"seat": "25"
},
{
"from": "Helsinki",
"to": "Tokio",
"transport": "NSB Regiontog Train",
"seat": "25"
},
{
"from": "Tokio",
"to": "Moscow",
"transport": "NSB Regiontog Train",
"seat": "25"
},
{
"from": "Paris",
"to": "New-York",
"transport": "NSB Regiontog Train",
"seat": "25"
},
{
"from": "Rome",
"to": "Oslo",
"transport": "NSB Regiontog Train",
"seat": "25"
}
]
结果必须是
- 赫尔辛基 - 东京
- 东京 - 莫斯科
- 莫斯科 - 罗马
- 罗马 - 奥斯陆
- 奥斯陆 - 巴黎
- 巴黎 - 纽约
最佳答案
<小时/>See also Sorting in JavaScript: Should every compare function have a "return 0" statement?
if (a.to != b.from) return 1;
if (a.to == b.from) return -1;
这不是一个一致的比较函数(违反了自反性,例如 compare(x, x) == 0
)。您希望它做什么?
If
comparefn
is […] not a consistent comparison function for the elements of this array, the behaviour of sort is implementation-defined.A function
comparefn
is a consistent comparison function for a set of valuesS
if all of the requirements below are met for all valuesa
,b
, andc
(possibly the same value) in the setS
: The notationa <CF b
meanscomparefn(a,b) < 0
;a =CF b
meanscomparefn(a,b) = 0
(of either sign); anda >CF b
meanscomparefn(a,b) > 0
.Calling
comparefn(a,b)
always returns the same valuev
when given a specific pair of valuesa
andb
as its two arguments. Furthermore,Type(v)
is Number, andv
is notNaN
. Note that this implies that exactly one ofa <CF b
,a =CF b
, anda >CF b
will be true for a given pair ofa
andb
.
- Calling
comparefn(a,b)
does not modify the this object.a =CF a
(reflexivity)- If
a =CF b
, thenb =CF a
(symmetry)- If
a =CF b
andb =CF c
, thena =CF c
(transitivity of=CF
)- If
a <CF b
andb <CF c
, thena <CF c
(transitivity of<CF
)- If
a >CF b
andb >CF c
, thena >CF c
(transitivity of>CF
)NOTE: The above conditions are necessary and sufficient to ensure that
comparefn
divides the setS
into equivalence classes and that these equivalence classes are totally ordered.
关于javascript - sort() 在 mozilla 和 opera 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600608/