call bind的实现以及数组常用方法

1.call 实现(apply 类似)

  Function.prototype.call= function(context){
      context = context || window;
      context.fn = this;
      let args =[];
      for(let i=1;i<arguments.length;i++){
          args.push('arguments[' + i + ']');
      }
      var result = eval("context.fn( " + args + ")");  // args 会调用toString()方法 
      delete context.fn;            “arguments[1],arguments[2]”   
      return result;
}

2.bind 实现

  Function.prototype.bind = function(context){
      let self = this;
      let proto = Array.prototype;
      let args =proto.slice.call(arguments,1);    // 调用bind方法传入的参数

      function forBind(){};
      forBind.prototype = this.prototype;     // 考虑到通过中间对象引用当前方法的原型
      let bindfun = function(){
          let lateArg = proto.slice.call(arguments);        // 调用bind后返回的方法传入的参数
          self.apply(context,args.contact(lateArg));
      }
      bindfun.prototype = new forBind();       //  指向当前方法的原型
      return bindfun;
}

3.array的几个常用方法

 forEach  (遍历数组中的元素)

  [1,2,3].forEach(function(item,idx,arr){  //item为每个元素idx为当前元素索引 arr 为当前数组 
      console.log(item + "--" + idx );
  })

 

 map (遍历数组  通过返回的值得到一个新的数组)

  let mapArr = [1,2,3].map(function(item,idx,arr){     
         return item *item;
  })
  console.log('mapArr---------:',mapArr)          //   mapArr---------: (3) [1, 4, 9]

filter(遍历数组   将返回为true的元素组成新的数组)
  let filterArr=[2,3,4].filter(function(item,idx,arr){
         return item %2 ==0;
  })

  console.log("filterArr----------------:",filterArr)     // filterArr----------------: (2) [2, 4]

 

every(遍历数组 每个元素符合条件返回true时 最终结果才为true)
  let everyBool = [1,2,3].every(function(item,idx,arr){
         return item >=1;

  })

  console.log("everyBool----------:",everyBool )       // everyBool----------: true

some(遍历数组 有一个元素符合条件返回true时 最终结果便为true)

  let someBool = [1,2,3].some(function(item,idx,arr){
         return item >=3;

  })

  console.log("someBool----------:",someBool)       // someBool----------: true

 

posted on 2020-06-02 23:19  swiftF  阅读(201)  评论(0编辑  收藏  举报

导航