|
| 1 | +/* |
| 2 | + * @Author: Chacha |
| 3 | + * @Date: 2022年05月06日 17:15:45 |
| 4 | + * @Last Modified by: Chacha |
| 5 | + * @Last Modified time: 2022年05月06日 19:52:19 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * map: 遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。 |
| 10 | + * |
| 11 | + * reduce: 对数组累积执行回调函数,返回最终计算结果。 |
| 12 | + * |
| 13 | + * @param {*} callback |
| 14 | + * @param {*} ctx |
| 15 | + * @returns |
| 16 | + * |
| 17 | + */ |
| 18 | +Array.prototype.map2 = function (callback, ctx = null) { |
| 19 | + if (typeof callback !== "function") { |
| 20 | + throw new Error("callback must be a function"); |
| 21 | + } |
| 22 | + |
| 23 | + return this.reduce( |
| 24 | + (result, cur, index, array) => |
| 25 | + result.concat(callback.call(ctx, cur, index, array)), |
| 26 | + [] |
| 27 | + ); |
| 28 | +}; |
| 29 | + |
| 30 | +let arr = [1, 2]; |
| 31 | +let arr1 = arr.map2( |
| 32 | + function (it, i, array) { |
| 33 | + console.log(it, i, array, this); |
| 34 | + return it * 2; |
| 35 | + }, |
| 36 | + { name: "Chacha" } |
| 37 | +); |
| 38 | + |
| 39 | +console.log("===================================="); |
| 40 | +console.log(arr1); |
| 41 | +console.log("===================================="); |
0 commit comments