sort()是按照字符编码的顺序进行排序;
<!doctype html> <htm> <head> <meta http-equiv="Content-type" content="text/html charset=utf-8"> <title></title> </head> <body> sort()是按照字符编码的顺序进行排序; </body> </html> <script type="text/javascript"> //例1:按字母顺序进行排序 var arr1 = new Array(6) arr1[0] = "George" arr1[1] = "Cohn" arr1[2] = "Thomas" arr1[3] = "James" arr1[4] = "Adrew" arr1[5] = "Bartin" console.log(arr1.sort()); //["Adrew", "Bartin", "Cohn", "George", "James", "Thomas"] //例2:按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数: function sortNumber(a,b){ return a - b; } var arr2 = new Array(6) arr2[0] = "10" arr2[1] = "5" arr2[2] = "40" arr2[3] = "25" arr2[4] = "1000" arr2[5] = "1" console.log(arr2.sort(sortNumber)); //["1", "5", "10", "25", "40", "1000"] //例3:根据数组对象中的某个属性值进行排序; var arr = [ {name:'zopp',age:0}, {name:'gpp',age:18}, {name:'yjj',age:8} ]; function compare(property){ return function(a,b){ var value1 = a[property]; var value2 = b[property]; return value1 - value2; } } console.log(arr.sort(compare('age'))); </script>
参考:
https://segmentfault.com/a/1190000000410506