数组封装新方法

//查找数组中符合条件的元素
Array.prototype.where = function (condition) {
var ret = [];
for (var i = 0; i < this.length; i++) {
if (condition(this[i])) {
ret.push(this[i]);
}
}
return ret;
};

 

 

//查找数组中第一个符合条件的元素
Array.prototype.first = function (condition) {
for (var i = 0; i < this.length; i++) {
if (condition(this[i])) {
return this[i];
}
}
return undefined;
}

 

//从数组中选择前n个元素
Array.prototype.top = function (count) {
var ret = [];
count = count < this.length ? count : this.length;
for (var i = 0; i < count; i++) {
ret.push(this[i]);
}
return ret;
}

 

posted @ 2023-02-06 14:19  喆星高照  阅读(1539)  评论(0)    收藏  举报