目录
1、概念
- 1、概念
- 2、MDN链接地址
- 3、代码
-
- 3.1、功能函数
- 3.2、函数调用
forEach()方法对数组的每个元素执行一次给定的函数。
2、MDN链接地址MDN - forEach
3、代码 3.1、功能函数Array.prototype.myforEach = function() { const len = this.length; // 获取传入的第一参数 // 回调函数 let callback = arguments[0] || this; // 获取传入的第二个参数 // 需要指向的this值 let thisArg = arguments[1] || this; // 如果this的长度为0,抛出错误 if (len == 0) { throw new TypeError('this is null or not defined'); }; // 如果传入的callback不是函数,抛出错误 if (typeof callback !== "function") { throw new TypeError(callback + 'is not a function'); }; let k = 0; while (k < len) { // if in this对象中是否含有k属性 // if('age' in data) data对象中是否含有age属性 if (k in this) { // this[k] --- item // k --- i // this --- data // 循环调用传进来的函数 // call改变this的指向 // 回调函数的作用是将循环出来的值返回到外面 callback.call(thisArg, this[k], k, this); }; k++; }; };3.2、函数调用
[10, 50, 90].myforEach((item, i, data) => { console.log(item); console.log(i); console.log(data); // 注意:使用箭头函数时, // this.a的值为undefined console.log(this.a); }, { a: 1 }); [10, 50, 90].myforEach(function(item, i, data) { console.log(item); console.log(i); console.log(data); // 注意 : 不使用箭头函数时, // this.a的值为传入的值 console.log(this.a); }, { a: 1 });