javascript字符串的自定义排序比较器

时间:2015-10-05 21:55:23

标签: javascript arrays sorting

我有一个自定义比较器,用于对某些字符串进行排序,这些字符串按预期方式按降序排序字符串。



var list = document.getElementById('mylist');

var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
  if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
    itemsArr.push(items[i]);
  }
}
var sortOrder = "DESC";

itemsArr.sort(function(a, b) {
  switch (sortOrder) {
    case "ASC":
      var val = a.innerHTML.localeCompare(b.innerHTML);
      break;
    case "DESC":
      var val = a.innerHTML.localeCompare(b.innerHTML);
      if (val === 1)
        val = -1;
      if (val === -1)
        val = 1;
      break;

  }
  return val
});

/*itemsArr.sort(function(a, b) {
  return a.innerHTML == b.innerHTML
          ? 0
          : (a.innerHTML > b.innerHTML ? 1 : -1);
});*/

for (i = 0; i < itemsArr.length; ++i) {
  list.appendChild(itemsArr[i]);
}
&#13;
<ul id="mylist">
  <li id="list-item3">Service</li>
  <li id="list-item4">Vendor</li>
  <li id="list-item2">Service_Type</li>
  <li id="list-item1">Call_Date</li>
  <li id="list-item3">Customer Sat Rating</li>
  <li id="list-item4">TTA</li>
  <li id="list-item2">Support_Rep</li>
  <li id="list-item1">Source_State</li>
  <li id="list-item3">Severity</li>
  <li id="list-item4">Customer_Type</li>
  <li id="list-item2">CALL ID</li>
  <li id="list-item1">Resolved_Ontime</li>
  <li id="list-item2">Product</li>
  <li id="list-item1">Minutes_On_Phone</li>
</ul>
&#13;
&#13;
&#13;

对于我之前排序的不同数据,它对升序和降序都很好。对于当前的html数据,它没有。有人可以告诉我哪里不对吗?

1 个答案:

答案 0 :(得分:2)

您将其设置为DESC,然后再将其设置为:

case "DESC":
  var val = a.innerHTML.localeCompare(b.innerHTML);
  if (val === 1)
    val = -1;
  if (val === -1)
    val = 1;
  break;

将其更改为:

case "DESC":
  var val = -1 * a.innerHTML.localeCompare(b.innerHTML);
  break;