Js extension methods are prototype-based, such as Array. prototype. XXXX is to extend the XXX Method to the Array, and then the Array can use this method. In the object Array, there are often sorting, ascending, and descending by attribute, next I will share with you a piece of knowledge I have written about the js prototype for a while. The js extension method is based on the prototype, such as Array. prototype. XXXX is to extend the XXX Method to the Array, and then the Array can use this method.
In the object array, attributes are often sorted in ascending or descending order, so I want to write a method similar to orderBy in C #. The Code is as follows:
The Code is as follows:
Array. prototype. OrderByAsc = function (func ){
Var m = {};
For (var I = 0; I <this. length; I ++ ){
For (var k = 0; k <this. length; k ++ ){
If (func (this [I]) <func (this [k]) {
M = this [k];
This [k] = this [I];
This [I] = m;
}
}
}
Return this;
}
Array. prototype. OrderByDesc = function (func ){
Var m = {};
For (var I = 0; I <this. length; I ++ ){
For (var k = 0; k <this. length; k ++ ){
If (func (this [I])> func (this [k]) {
M = this [k];
This [k] = this [I];
This [I] = m;
}
}
}
Return this;
}
The call method is as follows:
The Code is as follows:
Var arr = [{name: 'aaa', grade: 20}, {name: 'ccc ', grade: 30}, {name: 'bbb', grade: 40}];
Var orderArr = arr. OrderByDesc (function (){
Return a. grade;
});
Then, let's output the result:
The Code is as follows:
For (var I = 0; I <orderArr. length; I ++ ){
Document. write (orderArr [I]. name );
}
I am a js newbie. If you have any ideas, leave a message and exchange ideas with each other.