(method) Array<T>.forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void
- 看到
forEach
里的第一个参数是 callbackfn
: 回调方法,可以把数组里面的 value,index,list
全部返回给 callbackfn
方法里面。
const list = ['a', 'b', 'c', 'd'];
Array.prototype.newForEach = function (fn: (item: any, index: number,array: any[]) => void) {
console.log(this);
const len = this.length;
for (let i = 0; i < len; i++) {
fn(this[i], i,this);
}
};
list.newForEach((item, index) => {
console.log(item, index);
});
- 看到
forEach
里的第二个参数是 thisArg
:意思是指向回调函数的this
指向
var array1 = ['a', 'b', 'c'];
var array2 = ['1','2','3'];
array1.forEach(function(currentValue, index, arr) {
console.log(currentValue, index, arr, this);
},array2);
# 输出
> "a" 0 ["a", "b", "c"] ["1", "2", "3"]
> "b" 1 ["a", "b", "c"] ["1", "2", "3"]
> "c" 2 ["a", "b", "c"] ["1", "2", "3"]
const list = ['a', 'b', 'c', 'd'];
const list2 = [1, 2, 3];
Array.prototype.newForEach = function (
fn: (item: any, index: number, array: any[]) => void,
thisArg?: any,
) {
console.log(this);
const len = this.length;
for (let i = 0; i < len; i++) {
if (thisArg) {
fn.call(thisArg, this[i], i, this);
} else {
fn(this[i], i, this);
}
}
};
list.newForEach(function (currentValue, index, arr) {
console.log(currentValue, index, arr, this);
}, list2);