排序不过是按升序或降序显示元素。Array.sort()函数用于根据compare()
JavaScript中的函数对数组进行排序。
<html> <body> <script> var persons = [ { name: 'rajesh', birthdate: 1845, death: 1875 }, { name: 'Bharat', birthdate: 1909, death: 1917}, { name: 'baba', birthdate: 1950, death: 1972 }, { name: 'Tanish', birthdate: 2039, death: 2067 }, { name: 'rahim', birthdate: 1989, death: 2049 } ] var sortedArray = persons.sort(function(a,b) { var lastPerson = a.death - a.birthdate; var nextPerson = b.death - b.birthdate; if (lastPerson > nextPerson) { return -1; } else { return 1; } }); console.log(sortedArray); </script> </body> </html>
{name: "rahim", birthdate: 1989, death: 2049} {name: "rajesh", birthdate: 1845, death: 1875} {name: "Tanish", birthdate: 2039, death: 2067} {name: "baba", birthdate: 1950, death: 1972} {name: "Bharat", birthdate: 1909, death: 1917}
<html> <body> <script> var persons = [ { name: 'rajesh', birthdate: 1845, death: 1875 }, { name: 'Bharat', birthdate: 1909, death: 1917}, { name: 'baba', birthdate: 1950, death: 1972 }, { name: 'Tanish', birthdate: 2039, death: 2067 }, { name: 'rahim', birthdate: 1989, death: 2049 } ] var sortedArray = persons.sort(function(a,b) { var lastPerson = a.death - a.birthdate; var nextPerson = b.death - b.birthdate; if (lastPerson < nextPerson) { return -1; } else { return 1; } }); console.log(sortedArray); </script> </body> </html>
{name: "Bharat", birthdate: 1909, death: 1917} {name: "baba", birthdate: 1950, death: 1972} {name: "Tanish", birthdate: 2039, death: 2067} {name: "rajesh", birthdate: 1845, death: 1875} {name: "rahim", birthdate: 1989, death: 2049}