원본 분석

2866 단어
1. 콜 및 apply myCall로 콜 효과 구현
    Function.prototype.myCall=function(){
    	var ctx=arguments[0]||window;
    	ctx.fn=this;
    	var args=[];
    	var len=arguments.length;
    	for(var i=1;i

myApply 애플리케이션 효과 구현
Function.prototype.myApply = function (ctx, arr) {
            ctx = ctx || window;
            ctx.fn = this;
            var result;
            if (arr) {
                var args = [];
                for (var i = 0; i < arr.length; i++) {
                    args.push('arr[' + i + ']');
                }
                result = eval('ctx.fn(' + args.join(',') + ')');
            } else {
                result = ctx.fn();
            }
            delete ctx.fn;
            return result;
        }

2. 맵 및 reduceselfMap 맵 효과 구현
Array.prototype.selfMap = function () {
		  const ary = this
		  const result = []
		  const [ fn, thisArg ] = [].slice.call(arguments)
		  if (typeof fn !== 'function') {
			throw new TypeError(fn + 'is not a function')  
		  }
		  for (let i = 0; i < ary.length; i++) {
			result.push(fn.call(this, ary[i]))
		  }
		  return result
		}
		const a = new Array(1, 2, 3, 4,5);
		console.log(a.selfMap(item => item *2));

selfReduce 감소 효과 실현
Array.prototype.selfReduce= function (fn,init) {
		  var len=this.length;
		  var pre=init;
		  var i=0;
		  if(init==undefined){
			pre=this[0];
			i=1;
		  }
		  for(i;ipreTotal+ele));

3. reduce 실현맵과 filter reduce 실현맵
const reduceMap=(fn,thisArg)=>{
			return (list)=>{
				if(typeof fn!=="function"){
					throw new TypeError(fn+'is not a function');
				}
				if(!Array.isArray(list)){
					throw new TypeError('list not be a Array');
				}
				if(list.length==0) return []
				return list.reduce((acc,value,index)=>{
					return acc.concat([fn.call(thisArg,value,index,list)])
				},[]) 
			}
		}
		console.log(reduceMap(x=>x+1)([1,2,3]))

reduce 구현 filter
const reduceFilter=(fn,thisArg)=>{
			return (list)=>{
				if(typeof fn!=="function"){
					throw new TypeError(fn+'is not a function');
				}
				if(!Array.isArray(list)){
					throw new TypeError('list not be a Array');
				}
				if(list.length==0) return []
				return list.reduce((acc,value,index)=>{
					return fn.call(thisArg,value,index,list)?acc.concat([value]):acc
				},[])
			}
		}
		console.log(reduceFilter(x=>x%2===0)([1,2,3]))
		

기사 참조:https://juejin.im/post/5c0b7f03e51d452eec725729

좋은 웹페이지 즐겨찾기