手写js的map与forEach方法
/* 手写map方法 */ Array.prototype.myMap = function (fn, thisArg) { if (typeof fn !== 'function') { throw new Error(`${fn} is not function`) } let arr = this; let newArray = []; for (let i = 0; i < arr.length; i++) { newArray[i] = fn.call(thisArg, arr[i], i, arr) } return newArray } /* 手写forEach */ Array.prototype.myForEach = function (fun, thisArg) { if (typeof fun !== 'function') { return new Error('params error') } if (!Array.isArray(this)) { return `${this} is not array` } let oldArr = this; for (var k = 0; k < oldArr.length; k++) { console.log(thisArg) fun.call(thisArg, oldArr[k], k, oldArr) } } let arr = [1, 2, 3, 4] let res = arr.myForEach((item, index) => { return arr[index] = item * 2 }) console.log(arr)