如何在 JavaScript 中对数组排序?用示例说明?
排序
排序就是按照升序或降序显示元素。Array.sort() 函数用于根据 JavaScript 中的 compare() 函数对数组排序。
a) 在给定的程序中我们将按照 年龄属性降序对数组排序。
示例
<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}
b) 这里,我们按照年龄属性进行排序,以使数组升序排列
示例
<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}
广告