Home >Web Front-end >JS Tutorial >Implementation ideas for extending the OrderByAsc and OrderByDesc methods of js object array_javascript skills

Implementation ideas for extending the OrderByAsc and OrderByDesc methods of js object array_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 17:33:311581browse

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:

Copy code 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:
Copy code Code 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:
Copy code The code is as follows:

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.
Statement:
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