如何在javascript中排序字母数字数组

时间:2015-02-05 14:48:28

标签: javascript arrays sorting alphanumeric

我遇到了排序字母数字数组的问题。

排序模式编号首先是字母

09312d27-4ddc-458e-95dd-74531f787368,
1edcdde8-702e-4703-a505-ca81b77accdd,
.....

代码:

var alphaNumericArray = ['8a337e46-7d3f-46bc-b661-579f8d25fe09',
'09312d27-4ddc-458e-95dd-74531f787368',
'e7c5fba1-ce59-439a-a560-8f558e7c0ac4',
'1edcdde8-702e-4703-a505-ca81b77accdd',
'2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310',
'7529217d-ee80-41eb-ade7-208674924ab9',
'523f4f75-8d0a-4ad1-8f40-e8bc679956be',
'80871291-c8de-47d9-9b02-3f8444c5d64e',
'7529217d-ee80-41eb-ade7-208674924ab9'];

alphaNumericArray.sort(function(a, b) {
   a = a.value;
   b = b.value;
   return a-b;
});

//console.log(alphaNumericArray);
//alert(alphaNumericArray);

输出未排序。它在警报弹出窗口和控制台日志中显示相同的数组。

1 个答案:

答案 0 :(得分:2)

var alphaNumericArray = [
  '8a337e46-7d3f-46bc-b661-579f8d25fe09',
  '09312d27-4ddc-458e-95dd-74531f787368',
  'e7c5fba1-ce59-439a-a560-8f558e7c0ac4',
  '1edcdde8-702e-4703-a505-ca81b77accdd',
  '2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310',
  '7529217d-ee80-41eb-ade7-208674924ab9',
  '523f4f75-8d0a-4ad1-8f40-e8bc679956be',
  '80871291-c8de-47d9-9b02-3f8444c5d64e',
  '7529217d-ee80-41eb-ade7-208674924ab9'
];

alphaNumericArray.sort();

document.getElementById('out').textContent = JSON.stringify(alphaNumericArray, null, 2);
<pre id="out"></pre>

结果是:

[
  "09312d27-4ddc-458e-95dd-74531f787368",
  "1edcdde8-702e-4703-a505-ca81b77accdd",
  "2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310",
  "523f4f75-8d0a-4ad1-8f40-e8bc679956be",
  "7529217d-ee80-41eb-ade7-208674924ab9",
  "7529217d-ee80-41eb-ade7-208674924ab9",
  "80871291-c8de-47d9-9b02-3f8444c5d64e",
  "8a337e46-7d3f-46bc-b661-579f8d25fe09",
  "e7c5fba1-ce59-439a-a560-8f558e7c0ac4"
]

在此处阅读更多内容https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort