我有对象数组。我希望如果我在数组中添加对象,它应该以排序的方式添加。我使用数组进行排序。但它不对我的数组进行排序。这是我的代码
https://jsfiddle.net/8oczc5x5/
var arr = [{
elem: {
text: function() {
return "aa";
}
}
}, {
elem: {
text: function() {
return "yy";
}
}
}];
var obj = {
elem: {
text: function() {
return "bb";
}
}
}
arr.push(obj);
arr.sort()
console.log(arr[1].elem.text())
预期输出
"bb"
实际输出
"yy"
..为什么?我使用了 sort 它应该对我的数组进行排序吗?
最佳答案
sort
仅在按字母顺序对字符数据进行排序时才真正“开箱即用”。为什么您希望它调用您的函数并比较它们?这确实很危险而且很复杂。但是,您可以通过向其传递一个函数来执行您自己的特殊排序。
取自文档(compareFunction
是您传入的函数):
If
compareFunction
is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:If
compareFunction(a, b)
is less than 0, sort a to a lower index than b, i.e. a comes first.If
compareFunction(a, b)
returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.If
compareFunction(a, b)
is greater than 0, sort b to a lower index than a.compareFunction(a, b)
must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
arr.sort(function(a, b) {
// localeCompare does a string comparison that returns -1, 0, or 1
return a.elem.text().localeCompare(b.elem.text());
});
关于javascript - 为什么 array.sort 在 JavaScript 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949170/