时间:2021-07-01 10:21:17 帮助过:3人阅读
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;
}
调用的方法如下:
代码如下:输出一下,看一下结果吧:
var arr = [{ name: 'aaa', grade: 20 }, { name: 'ccc', grade: 30 }, { name: 'bbb', grade: 40 }];
var orderArr = arr.OrderByDesc(function (a) {
return a.grade;
});
然后
代码如下:
for (var i = 0; i < orderArr.length; i++) {
document.write(orderArr[i].name);
}
本人js菜鸟,如果有什么想法啥的,直接留言,相互交流一下