1、forEach
Array.prototype.my_forEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
2、map
Array.prototype.my_map = function (callback) {
const arr = [];
for (let i = 0; i < this.length; i++) {
arr.push(callback(this[i], i, this));
}
return arr;
};
3、filter
Array.prototype.my_filter = function (callback) {
const arr = [];
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this) && arr.push(this[i]);
}
return arr;
};
4、every
Array.prototype.my_every = function (callback) {
let flag = true;
for (let i = 0; i < this.length; i++) {
flag = callback(this[i], i, this);
if (!flag) break;
}
return flag;
};
5、some
Array.prototype.my_some = function (callback) {
let flag = false;
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
flag = true;
break;
}
}
return flag;
};
使用
const arrTest = [
{ name: "caix-1987", age: 24 },
{ name: "caix-1988", age: 23 },
{ name: "caix-1989", age: 22 },
];
arrTest.my_forEach((item, index, arr) => {
console.log("my_forEach", item, index, arr);
});
const my_map_data = arrTest.my_map((item) => {
return item.age;
});
const my_filter_data = arrTest.my_filter((item) => {
return item.age > 23;
});
const my_every_data = arrTest.my_every((item) => {
return item.age > 23;
});
const my_some_data = arrTest.my_some((item) => {
return item.age > 23;
});
标签:map,arr,return,callback,some,第九篇,item,const,my
From: https://www.cnblogs.com/caix-1987/p/17308250.html