javascript - 为什么 array.sort 在 JavaScript 中不起作用?

标签 javascript jquery arrays sorting

我有对象数组。我希望如果我在数组中添加对象,它应该以排序的方式添加。我使用数组进行排序。但它不对我的数组进行排序。这是我的代码

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/

相关文章:

javascript - h1 标签不随 bootstrap 改变颜色

java - 创建数组的数组列表

javascript - 如何突出显示菜单按钮?

javascript - 如何正确管理 AJAX 的快速输入?

javascript - 在嵌套 iframe 内使用/安装库

javascript - Google PlusOne 的这个功能有什么作用?

jquery - 用 jquery 动画 div

python - 从数组值过滤字典

javascript - 为什么这个 React 组件返回字符串 '0'

javascript - 在顺序 javascript 数组中查找范围的最有效方法