前端功能函数整理(持续更新)

165 阅读1分钟

文件下载

function downloadFile() {
    const fileName = `${this.dialogData.name }.yaml`;
    const data = this.yaml;
    const blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' });
    const fileUrl = URL.createObjectURL(blob);
    const downEle = document.createElement('a');
    const a = document.body.appendChild(downEle);
    a.setAttribute('href', fileUrl);
    a.setAttribute('download', fileName);
    a.click();
    document.body.removeChild(downEle);
    URL.revokeObjectURL(fileUrl);
}

计算UTF-8字符串占内存大小

function strSize(str) {
    let total = 0;
    for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        if (charCode <= 0x007f) {
            total += 1;
        } else if (charCode <= 0x07ff) {
            total += 3;
        } else {
            total += 4;
        }
    }
    return total;
}