The JSON content returned by AJAX is sorted using the sort () method

Time:2021-9-8

Key methods:Sort() is used to sort the elements of the array.
Return a.num-b.num is in ascending order;
return b.num-a.num; It’s in descending order
Writeln adds \ n after the output, which is a line feed in the document and an explanatory space in HTML.

Copy codeThe code is as follows:
$.post(“json.json”,function(data){
data.sort(function(a,b){return a.num-b.num;});
for(var i=0;i<data.length;i++){
var nums=data[i].num;
document.writeln(nums);
}
},”json”)

JSON data:
[
{
“num”:”5″
},
{
“num”:”1″
},
{
“num”:”3″
},
{
“num”:”2″
}
]