常用工具方法

下载

下载图片(移动端)

function savePicture(Url: string) {
  const blob = new Blob([''], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = Url
  a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0]
  const e = new MouseEvent('click')
  a.dispatchEvent(e)
  URL.revokeObjectURL(url)
}

下载文本

function downloadText(fileName, text) {
    const url = window.URL || window.webkitURL || window;
    const blob = new Blob([text]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    saveLink.href = url.createObjectURL(blob);
    // 设置 download 属性
    saveLink.download = fileName;
    saveLink.click();
}

下载 json

function downloadJson(fileName, json) {
    const jsonStr = (json instanceof Object) ? JSON.stringify(json) : json;
    
    const url = window.URL || window.webkitURL || window;
    const blob = new Blob([jsonStr]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    saveLink.href = url.createObjectURL(blob);
    saveLink.download = fileName;
    saveLink.click();
}

排序

洗牌数组

Array.prototype.shuffle = function() {
    const array = this;
    let m = array.length,
        t, i;
    while (m) {
        i = Math.floor(Math.random() * m--);
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    return array;
}
Comments
Write a Comment