0
点赞
收藏
分享

微信扫一扫

汇总常用的js方法

十里一走马 2021-09-24 阅读 106
Js前端
  1. call 方法 (调用时,改变)

目的:在执行函数时,改变当前的执行上下文 指向;

  //context: 表示 window 或者自定义的 上下文; 拦截到 函数调用时机
    Function.prototype.mCall = function(context) {
        //1. 执行上下文初始化
        context = context || window;
        console.log(this)// f test() {}
        //2. 绑定调用的函数
        context.fn = this;
        //3. 分离函数的参数
        let args = [...arguments].slice(1)
        console.log(args);
        //4. 调用函数
        let result = context.fn(...args);
        //5. 销毁调用函数
        Reflect.deleteProperty(context, "fn");
        return result;
    }

    //使用
 // test.mApply(person,1,2,3);
  1. apply 方法 (调用时,改变)

目的:在执行函数时,改变当前的执行上下文 指向, 与 call区别参数不一样;

 Function.prototype.mApply = function(context) {
    context = context || window;
    context.fn = this;
    let result;
    if(arguments[1]) {
        result = context.fn(...arguments[1]);
    }else {
        result = context.fn();
    }
    Reflect.defineProperty(context, "fn");
    return result;
}
//使用
 // test.mApply(person,1,2,3);
  1. bind 方法 (新建时,改变)

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用

 Function.prototype.mBind = function(context) {
        //1. 绑定时分离参数
        let args = [...arguments].slice(1);
        //2. 定义个构造函数
        let F = function() {};
        //3. 绑定this
        let _this = this;
        //4. 定义一个返回(绑定)函数
        let bound = function() {
            //4.1 合并参数,绑定和调用的
            let finalArgs = [...args, ...arguments]
                // 改变作用域,注:aplly/call是立即执行函数,即绑定会直接调用
            // 这里之所以要使用instanceof做判断,是要区分是不是new xxx()调用的bind方法
            return _this.call((this instanceof F? this: context), ...finalArgs);
        }
        //5. 将调用函数的原型赋值到中转函数的原型上
        F.prototype = _this.prototype;
        //6. 通过原型的方式继承调用函数的原型
        bound.prototype = new F();
        return bound;
    }

  1. 函数柯里化

函数的参数可以 分步 传入; 参数复用

  function curry(fn) {
        return function(...args) {
            if(args.length >= fn.length) {
                return fn.apply(this, args) //window.fn(args)
            }else {
                return function(...args2) {
                    return fn.apply(this, args.concat(args2))
                } 
            }
        }
    }
  1. debounce和throttle

debounce防抖:让某一个时间段内,事件只触发一次, scroll事件;throttle节流:想让触发回调函数的频率降低,在某一时间内回调函数是失效状态。 input resize 事件

    function debounce(fn, wait) {
        let timer = null;
        return function() {
            if(timer) { clearTimeout(timer)};
            let _this = this;
            let args = arguments;
            timer = setTimeout(() => {
                fn.apply(_this, args)
            }, wait);
        }
    }

    function throttle(fn, wait) {
        let previous = 0;
        return function() {
            let _this = this;
            let args = arguments;
            let now = new Date().getTime()//时间戳
            if(now - previous >= wait) {
                fn.apply(_this, args);
                previous = now;
            }
        }
    }
  1. 深拷贝和浅拷贝

深浅拷贝是针对 引用数据类型;
对于浅拷贝而言,就是只拷贝对象的引用,而不深层次的拷贝对象的值,多个对象指向堆内存中的同一对象,任何一个修改都会使得所有对象的值修改,因为它们公用一条数据
深拷贝不会拷贝引用类型的引用,而是将引用类型的值全部拷贝一份,形成一个新的引用类型,这样就不会发生引用错乱的问题,使得我们可以多次使用同样的数据,而不用担心数据之间会起冲突

浅拷贝实现

  • JSON.stringify() 、 JSON.parse()

是否支持深拷贝多层引用类型嵌套:支持
不可以拷贝 undefined , function, RegExp 等类型的数据

  • 展开运算符...

是否支持深拷贝多层引用类型嵌套:不支持

  • Object.assign(target, source)
    是否支持深拷贝多层引用类型嵌套:不支持

深拷贝实现

是否支持深拷贝多层引用类型嵌套:支持

// 定义一个深拷贝函数  接收目标target参数
function deepClone(target) {
    // 定义一个变量
    let result;
    // 如果当前需要深拷贝的是一个对象的话
    if (typeof target === 'object') {
    // 如果是一个数组的话
        if (Array.isArray(target)) {
            result = []; // 将result赋值为一个数组,并且执行遍历
            for (let i in target) {
                // 递归克隆数组中的每一项
                result.push(deepClone(target[i]))
            }
         // 判断如果当前的值是null的话;直接赋值为null
        } else if(target===null) {
            result = null;
         // 判断如果当前的值是一个RegExp对象的话,直接赋值    
        } else if(target.constructor===RegExp){
            result = target;
        }else {
         // 否则是普通对象,直接for in循环,递归赋值对象的所有值
            result = {};
            for (let i in target) {
                result[i] = deepClone(target[i]);
            }
        }
     // 如果不是对象的话,就是基本数据类型,那么直接赋值
    } else {
        result = target;
    }
     // 返回最终结果
    return result;
}

简化


function deepClone(data) {
    if (typeof data === "object") {
      var result = Array.isArray(data) ? [] : {};
      for (var key in result) {
        if (typeof result[key] === "object") {
          result[key] = deepClone(data[key]);
        } else {
          result[key] = data[key];
        }
      }
    } else {
      return data;
    }
  }

7. 线性结构和树形结构转换

let array = [
  {
    id: 1,
    parent_id: 0,
    name: "四川省"
  },
  {
    id: 2,
    parent_id: 0,
    name: "广东省"
  },
  {
    id: 3,
    parent_id: 0,
    name: "江西省"
  },
  {
    id: 5,
    parent_id: 1,
    name: "成都市"
  },
  {
    id: 6,
    parent_id: 5,
    name: "锦江区"
  },
  {
    id: 7,
    parent_id: 6,
    name: "九眼桥"
  },
  {
    id: 8,
    parent_id: 6,
    name: "兰桂坊"
  },
  {
    id: 9,
    parent_id: 2,
    name: "东莞市"
  },
  {
    id: 10,
    parent_id: 9,
    name: "长安镇"
  },
  {
    id: 11,
    parent_id: 3,
    name: "南昌市"
  }
]

function listToTree(list) {

  let map = {};
  //
  list.forEach(item => {
    if (! map[item.id]) {

      map[item.id] = item;
    }
  });
  console.log(map)
  console.log(list)
  list.forEach(item => {
    if (item.parent_id !== 0) {
      map[item.parent_id].children ? map[item.parent_id].children.push(item) : map[item.parent_id].children = [item];
    }
  });
  console.log(list)
  return list.filter(item => {
    if (item.parent_id === 0) {
      return item;
    }
  })
}
console.log(listToTree(array));

8. es6+ 有关方法实现 例如 flat

敬请期待

举报

相关推荐

0 条评论