JavaScript sort() 方法
sort() 方法用于对数组的元素进行排序。
规定排序顺序。必须是函数。
而且数组在原数组上进行排序,不生成副本。
例子 1
创建一个数组,并按字母顺序进行排序:
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") document.write(arr.sort()) </script>
输出:
George,John,Thomas,James,Adrew,Martin Adrew,George,James,John,Martin,Thomas
例子 2
创建一个数组,并按字母顺序进行排序:
<script type="text/javascript"> var arr = new Array(6) arr[0] = "10" arr[1] = "5" arr[2] = "40" arr[3] = "25" arr[4] = "1000" arr[5] = "1" document.write(arr + "<br />") document.write(arr.sort()) </script>
输出:
10,5,40,25,1000,1 1,10,1000,25,40,5
注意,上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数:
<script type="text/javascript"> function sortNumber(a,b) { return a - b } var arr = new Array(6) arr[0] = "10" arr[1] = "5" arr[2] = "40" arr[3] = "25" arr[4] = "1000" arr[5] = "1" document.write(arr + "<br />") document.write(arr.sort(sortNumber)) </script>
输出:
10,5,40,25,1000,1 1,5,10,25,40,1000
例子 3
创建一个数组,并按数组里面集合中x的元素进行排序:
<script type="text/javascript"> var arr = new Array(6) arr[0] = {x: '10', y: 'George'} arr[1] = {x: '5', y: 'John'} arr[2] = {x: '40', y: 'Thomas'} arr[3] = {x: '25', y: 'James'} arr[4] = {x: '1000', y: 'Adrew'} arr[5] = {x: '1', y: 'Martin'} function compare(property) { return function(a, b) { var value1 = a[property]; var value2 = b[property]; return value1 - value2; }; } console.log(JSON.parse(JSON.stringify(arr))); console.log(arr.sort(compare('x'))); </script>
输出:
{x: '10', y: 'George'}, {x: '5', y: 'John'}, {x: '40', y: 'Thomas'}, {x: '25', y: 'James'}, {x: '1000', y: 'Adrew'}, {x: '1', y: 'Martin'}
{x: '1', y: 'Martin'}, {x: '5', y: 'John'}, {x: '10', y: 'George'}, {x: '25', y: 'James'}, {x: '40', y: 'Thomas'}, {x: '1000', y: 'Adrew'}