JS 通用方法

  1. 获取文件后缀
export const getFileSuffix = (filename) => {
    let idx = filename.lastIndexOf(".") + 1;
    return filename.substring(idx);
};
  1. 简单date方法
export const add0 = (i) => {

    if(i < 10){
        return "0" + i;
    }else {
        return  i;
    }

}

export function date(timestamp) {

    let date = new Date(parseInt(timestamp)*1000);

    let y = date.getFullYear();
    let m = add0(date.getMonth()+1);
    let d = add0(date.getDate());
    let h = add0(date.getHours());
    let i = add0(date.getMinutes());
    let s = add0(date.getSeconds());

    return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;

}

export function getFullDay(timestamp) {

    let date = new Date();
    if(timestamp) {
        date = new Date(parseInt(timestamp) * 1000);
    }

    return date.getFullYear() + add0(date.getMonth() + 1) + add0(date.getDate());

}
  1. 随机字符串
export const randomString = (len,type) => {

    type = type || 1;
    let chars1 = ['0','1','2','3','4','5','6','7','8','9'];
    let chars2 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    let chars3 = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    let chars = chars1;
    let max = 9;
    if(type === 2) {
        chars = chars2;
        max = 35;
    }else if (type === 3) {
        chars = chars3;
        max = 61;
    }

    let res = "";
    for(let i = 0; i < len ; i ++) {
        let idx = Math.ceil(Math.random()*max);
        res += chars[idx];
    }

    return res;

};

你可能感兴趣的:(JS 通用方法)