javascript-手写reduce()/通过reduce()实现map()

loading 2023年02月20日 95次浏览
  • 参数:一个回调函数,一个初始化参数 (非必须)
  • 回调函数参数有 4 个值
    • prev: 上一次调用 callbackFn 时的返回值
    • cur: 数组中正在处理的元素
    • index: 数组中正在处理的元素的索引
    • arr 用于遍历的数组
  • 返回total累加值
        Array.prototype.myReduce = function(fn, init) {
            if(!Array.isArray(this)) throw new TypeError('123');
            if(!this.length && !arguments[1]) throw new Error('...')
            let arr = this, total = null;

            if(arguments[1]) {
                total = init;
            } else {
                total = arr.shift();
            }

            for(let i = 0 ; i < arr.length ; i++) {
                total = fn(total, arr[i], i, arr);
            }
            return total;
        }

	let arr = [1,2,3,4];
	let res = arr.myReduce((total , cur) => total + cur, 10);
	console.log(res); //20

这里额外补充一个reduce实现map的方法,美团一面考到的,面试的时候没写出来:

当时面试的时候想太复杂了,没想明白怎么把reduce的pre给用到map上来实现类似于累加之类的效果,因为感觉map用不到pre这个参数?

结果其实实现过程就只是把reduce的后三个参数拿过来给map用而已:

        Array.prototype.myReduceMap = function(fn, thisArg = window) {
            let res = [];
            this.reduce(function(total, cur, index, arr) {
                return res.push(fn.call(thisArg, cur, index, arr));
            }, []);
            return res;
        }

        let arr = [2, 3, 1, 5];
        console.log(arr.myMap1(x => x + 1))