前端常用方法集合

使用generator生成字符串0-9a-Z

function* generateSequence(start, end) {
    for (let i = start; i <= end; i++) yield i;
  }
  
  function* generateAlphaNum() {
    yield* generateSequence(48, 57);
    yield* generateSequence(65, 90);
    yield* generateSequence(97, 122);
  }
  
  let str = '';
  
  for(let code of generateAlphaNum()) {
    str += String.fromCharCode(code);
  }
  
  console.log(str); // 0..9A..Za..z

先定义一个对象然后从明白对象中要获取想要的值

const modelObjet = {
  a: "",
  c: {
    g: "",
  },
};

const targetObjet = {
  a: "1",
  b: "2",
  hh: "1213",
  c: {
    f: "",
    g: "test",
  },
  h: 5,
};

function recurrenceObj(modelObj = {}, targetObjet = {}) {
  let tempObj = {};
  Object.keys(modelObj).map((item) => {
    if (typeof modelObj[item] !== "object") {
      tempObj[item] = targetObjet[item];
    } else {
      tempObj[item] = recurrenceObj(modelObj[item], targetObjet[item]);
    }
  });
  return tempObj;
}
const result = recurrenceObj(modelObjet,targetObjet)

深拷贝

const deepClone = (object) => {
            const tempObj = object instanceof Array ? [] : {};
            for (const key in object) {
                if (typeof object[key] === 'object') {
                    tempObj[key] = deepClone(object[key]);
                } else {
                    tempObj[key] = object[key];
                }
            }
            return tempObj
        }

手动实现 new 操作符

function myNew() {
    const Constructor = arguments[0],
        args = [...arguments].slice(1), // arguments是类数组,因此需要转换为数组才能使用slice方法
        obj = {};
    Constructor.apply(obj, args);
    // 设置[[prototype]]指针(推荐)
    Object.setPrototypeOf(obj, Constructor.prototype);
    return obj;
}

// 调用
function Person(name, age) {
    this.name = name;
    this.age = age;
}
myNew(Person, 'tom', 23);

// canvas截图保存本地

class SaveToLocal {
    base64Img2Blob(code) {
        let parts = code.split(";base64,");
        let contentType = parts[0].split(":")[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {
            type: contentType
        });
    }
    downloadFile(fileName, content) {
        let aLink = document.createElement("a");
        let blob = this.base64Img2Blob(content);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.click();
    }

    download = async (filename) => {
        filename = `${filename ?? 'pic'}_${Date.now()}`;
        // this.canvas你的canvas
        this.downloadFile(filename, this.canvas.toDataURL("image/png"));
    }
}


const t = new SaveToLocal()

t.download()

天气接口API

http://wthrcdn.etouch.cn/weather_mini?city=广州
http://wthrcdn.etouch.cn/WeatherApi?city=广州

获取城市接口

http://pv.sohu.com/cityjson?ie=utf-8

获取随机数

function random(min, max) {
  return min + Math.random() * (max - min);
}

获取随机整数

function randomInteger(min, max) {
  let rand = min + Math.random() * (max + 1 - min);
  return Math.floor(rand);
}

计算随机数

function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
      let j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }

防抖

function debounce(fn, ms) {
    let timeout;
    return function () {
        clearInterval(timeout)
        timeout = setTimeout(() => {
            fn.apply(this, arguments)
        }, ms);
    }
}

节流

function throttle(func, ms) {

    let isThrottled = false,
      savedArgs,
      savedThis;
  
    function wrapper() {
  
      if (isThrottled) { // (2)
        savedArgs = arguments;
        savedThis = this;
        return;
      }
  
      func.apply(this, arguments); // (1)
  
      isThrottled = true;
  
      setTimeout(function() {
        isThrottled = false; // (3)
        if (savedArgs) {
          wrapper.apply(savedThis, savedArgs);
          savedArgs = savedThis = null;
        }
      }, ms);
    }
  
    return wrapper;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值