1. forEach()
forEach()方法可接收两个参数。
通常情况下,我们只知道接收一个回调函数,但其实它有第二个参数
参数1: 回调函数,(item, index, originArr) item: 数组的每一项, index:索引,originArr:原数组。
参数2:_this ,要修改的this指向, 不写第二个参数,默认指向的是 window
const arr = ["a", "b", "c"];
const o = { age: 18 };
arr.forEach(function (item, index, originArr) {
console.log(item, index, originArr, this); // 默认指向 window
}, o); // 现在指向 对象 o
// a 0 (3) ['a', 'b', 'c'] {age: 18}
弄明白了 forEach 方法的参数问题现在来实现自己手写封装一个 forEach 方法:
Array.prototype.forEachfn = function () {}
正如上面这个 手写完成后 forEachfn 应该和 forEach 的方法一致。
const arr = ["a", "b", "c"];
const o = { age: 18 };
Array.prototype.forEachfn = function (callback, _this = window) {
// this => arr this 指向调用它的数组
for (let i = 0; i < this.length; i++) {
// callback.call(this[i], i, this);
callback.call(_this, this[i], i, this);
}
};
arr.forEachfn(function (item, index, originArr) {
console.log(item, index, originArr, this); // 默认指向 window
}, o); // 现在指向 对象 o
/* a 0 (3) ['a', 'b', 'c'] {age: 18}
b 1 (3) ['a', 'b', 'c'] {age: 18}
c 2 (3) ['a', 'b', 'c'] {age: 18} */
第一个参数 callback 一上来就调用 调用次数由数组的长度决定
第二个参数 _this 用来修改 this 指向 _this = window 让其默认指向window
回调函数中 callback.call(this[i], i, this); 中的三个参数一一对应:item, index, originArr
通过 call() 来修改 this 指向问题 callback.call(_this, this[i], i, this); _this 就是传递过来的第二个参数,修改 this 指向。
至此完成封装,和 原方法效果一致。
2. filter()
filter() 方法用来筛选过滤符合条件的数组。
const arr = [7, -9, 5, 1, -11, 19];
Array.prototype.filterfn = function (callback) {
const newArr = []; // 声明一个空数组 用来装筛选出来的新数组,最后返回这数组
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
newArr.push(this[i]);
}
}
return newArr;
};
console.log(arr.filterfn((item) => item < 0));
// [-9, -11]
3. map()
map() 映射数组每一个元素,进行修改
const arr = ['a', 'b', 'c']
Array.prototype.mapfn = function (callback) {
const newArr = []
for (let i = 0; i < this.length; i++) {
newArr.push(callback(this[i], i, this))
// this[i] => item, i => index, this => originArr
}
return newArr
}
console.log(arr.mapfn((item, index, originArr) => '~' + item + '~'))
// ['~a~', '~b~', '~c~']
4. sort()
sort() 进行数组排序,升序或者降序
const arr = [7, 9, 5, 1, 11, 19];
Array.prototype.sortfn = function (callback) {
// 把【排序】好的结果返回出去
for (let i = 0; i < this.length - 1; i++) {
for (let j = 0; j < this.length - i - 1; j++) {
if (callback(this[j], this[j + 1]) > 0) {
[this[j], this[j + 1]] = [this[j + 1], this[j]];
}
}
}
return this;
};
console.log(arr.sortfn((a, b) => a - b));
// a-b 升序 [1, 5, 7, 9, 11, 19]
// b-a 降序 [19, 11, 9, 7, 5, 1]
进行双重 for 循环排序 判断 item 大小 在交换两个变量
let temArr = [];
temArr = this[j];
this[j] = this[j + 1];
this[j + 1] = temArr;
上面这个方法交换两个变量效果一样 如果代码中的方法不好理解可以尝试这个方法。