Home > Web Front-end > JS Tutorial > body text

Example code of js function sorting_javascript skills

WBOY
Release: 2016-05-16 17:30:43
Original
1014 people have browsed it
Copy code The code is as follows:

var as = [1,2,11,3434,3,4545 ,33,55,0];
as.sort(); //This sorting is based on dictionary sorting
//Customized sorting based on numbers
function sortByNum(a,b){
return parseInt(a) - parseInt(b);
}
as.sort(sortByNum);
//Sort by objects
//Define a person object
function Person(name. age){
this.name=name;
this.age=age;
}
var p1 = new Person("zhang1",11);
var p2 = new Person( "zhang2",1);
var p3 = new Person("zhang3",18);
var p4 = new Person("zhang4",13);
var ps = [p1,p2, p3,p4];
function sortByName(obj1,obj2){
if(obj1.name>obj2.name){return 1}
else if(obj1.name==obj2.name){return 0}
else{return -1}
}
function sortByAge(obj1,obj2){
return obj1.age - obj2.age;
}
ps.sort(sortByName ) // Sort by name
ps.sort(sortByAge) // Sort by age

The problem caused by the above sorting is that assuming that the object has many attributes, then how many attributes should our program have? Set the sorting rules separately. So there is the following method:
Copy code The code is as follows:

function sortByProperty(proName) {
var sortFun = function(obj1,obj2){
if(obj1[proName]>obj2[proName]) {return 1}
else if(obj1[proName]==obj2[proName] ) {return 0}
else {return -1}
}
return sortFun;
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!