After reading about js prototypes for a while, I found that the extension methods of js are based on prototypes. For example, Array.prototype.XXXX extends the XXX method to Array, and then all arrays can use this method.
Object arrays are often sorted according to attributes, in ascending order and descending order, so I wanted to write a method similar to orderBy in C#. 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 method called is as follows:
var arr = [{ name: 'aaa', grade: 20 }, { name: 'ccc', grade: 30 }, { name: 'bbb', grade: 40 } ];
var orderArr = arr.OrderByDesc(function (a) {
return a.grade;
});
Then output it and see the result:
for (var i = 0; i < orderArr.length ; i ) {
document.write(orderArr[i].name);
}
I am a novice in js. If you have any ideas, please leave a message directly and communicate with each other.