手写forEach
let arr = [1, 2, 3, 4];
Array.prototype._forEach = function (fn) {
for (let i = 0; i < this.length; i++) {
fn(this[i], i);
}
};
arr._forEach(function (item, index) {
console.log(item, index);
});
手写map
let arr = [1, 2, 3, 4];
Array.prototype._map = function (fn) {
let res = [];
for (let i = 0; i < this.length; i++) {
res.push(fn(this[i], i));
}
return res;
};
let res = arr._map((item, index) => item * 2);
console.log(res);
手写filter
let arr = [1, 2, 3, 4];
Array.prototype._filter = function (fn) {
let res = [];
for (let i = 0; i < this.length; i++) {
if (fn(this[i], index)) {
res.push(this[i]);
}
}
return res;
};
let res1 = arr._filter((item, index) => item > 2);
console.log(res1);
手写find
let obj = [
{
a: 1,
id: 1,
},
{
b: 2,
id: 2,
},
];
//find
Array.prototype._find = function (fn) {
// let res=null;
for (let i = 0; i < this.length; i++) {
if (fn(this[i], i)) {
return this[i];
}
}
};
let res2 = obj._find((item) => item.id == 2);
console.log(res2);
手写findIndex
let obj = [
{
a: 1,
id: 1,
},
{
b: 2,
id: 2,
},
];
Array.prototype._findIndex = function (fn) {
// let res=null;
for (let i = 0; i < this.length; i++) {
if (fn(this[i], i)) {
return i;
}
}
};
let res3 = obj._findIndex((item) => item.id == 2);
console.log(res3);
手写every
//every
let arr = [1, 2, 3, 4];
Array.prototype._every = function (fn) {
for (let i = 0; i < this.length; i++) {
if (!fn(this[i])) {
return false;
}
}
return true;
};
let res4 = arr._every((item) => item > 2);
console.log(res4);
手写some
let arr = [1, 2, 3, 4];
Array.prototype._some = function (fn) {
for (let i = 0; i < this.length; i++) {
if (fn(this[i])) {
return true;
}
}
return false;
};
let res5 = arr._some((item) => item > 2);
console.log(res5);
手写reduce
//reduce
let arr = [1, 2, 3, 4];
Array.prototype._reduce = function (fn, initVal) {
let acc = initVal;
if (acc == undefined) {
acc = this[0];
for (let i = 1; i < this.length; i++) {
acc = fn(acc, this[i], i, this);
}
} else {
for (let i = 0; i < this.length; i++) {
acc = fn(acc, this[i]);
}
}
return acc;
};
let res6 = arr._reduce((acc, item) => acc + item, 0);
console.log(res6);
手写new
//手写new
function myNew(fn, ...args) {
console.log(args); // ['占山', 21]
const obj = {};
obj.__proto__ = fn.prototype;
fn.apply(obj, args); //改变this指向
return obj;
}
function Person(name, age) {
this.name = name;
this.age = age;
}
let p = myNew(Person, "zs", 21);
console.log(p);