一些常用的 js 方法

155 阅读1分钟

1. 文件

1.1 blob 转为 base64

export const blobToBase64 = (blob, cb) => {
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    return cb(e.target.result);
  };
  fileReader.readAsDataURL(blob);
};

1.2 file 转为 base64

export const fileToBase64 = (file, cb) => {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function (e) {
    return cb(e.target.result);
  };
};

2. 格式 相关

/**
 * @desc 判断字符串是否为JSON格式
 * @author qiuer
 * @param {String} str 需要判断的字符串
 * @returns   {BOOlean}    [返回布尔值]
 */
function strIsJSON(str){
    if (typeof str === 'string'){
    try {
        var obj = JSON.parse(str);
        if(typeof obj === 'object' && obj){
        return true;
        }else{
        return false;
        }
    } catch (e) {
        return false;
    }
    }
    return false;
}
/**
 * @desc JSON格式化
 * @author qiuer
 * @param {String} str 需要格式化的字符串
 * @returns   {String}    [返回格式化结果]
 */
function formatJson(str){
    if(strIsJSON(str)) {
        return JSON.stringify(JSON.parse(str), null, 4);
    } else {
        return str;
    }
}
/**
 * @desc 时间转换,如: 1000ms转换成1s,当不传oldUnit、newUnit时默认val是单位是ms,并对其根据值得大小进行转换
 * @author qiuer
 * @param {String|Number} val 时间值
 * @param {String} oldUnit 时间转换前单位,可取值: ms、s
 * @param {String} newUnit 时间转换后单位,可取值: ms、s
 * @returns   {null}    [没有返回]
 */
function transferTime(val, oldUnit, newUnit){
    if(!oldUnit || !newUnit){
        if(val >= 3600000){ // 时
            return `${(val/3600000).toFixed(2)}h`;
            // const h = Math.floor(val / 3600000); // 小时
            // const hRemainder = val % 3600000; // 小时的余数
            // const m = Math.floor(hRemainder / 60000); // 分钟
            // const mRemainder = hRemainder % 60000; // 分钟的余数
            // const s = Math.floor(mRemainder / 1000); // 秒
            // const sRemainder = mRemainder % 1000; // 秒的余数
            // return `${h}h${m}min${s}s${sRemainder}ms`;
        }else if(val >= 60000){ // 分
            return `${(val/60000).toFixed(2)}min`;
        }else if(val >= 1000){ // 秒
            
            return `${(val/1000).toFixed(2)}s`;
        }
        return `${val}ms`;
    }
    return `${val}ms`;
}
/**
 * @desc 将时间戳转换成日期格式
 * @author qiuer
 * @param {String|Number} timestamp 时间戳
 * @returns   {String}    [返回日期格式]
 */
function timestampToTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s;
}
/**
 * @desc 时长转换
 * @author qiuer
 * @param {String|Number} 毫秒时长
 * @returns   {String}    [返回日期格式]
 */
function transferDuration(duration){
    let result = '';
    if(duration/86400000 > 1){
        result += `${Math.floor(duration/86400000)}D`;
    }
    if((duration%86400000)/3600000 > 1){
        result += `${Math.floor((duration%86400000)/3600000)}h`;
    }
    if(((duration%86400000)%3600000)/60000 > 1){
        result += `${Math.floor(((duration%86400000)%3600000)/60000)}m`;
    }
    if((((duration%86400000)%3600000)%60000)/1000 > 1){
        result += `${Math.floor((((duration%86400000)%3600000)%60000)/1000)}s`;
    }
    if(duration < 60000 && duration > 1000){
        result += `${duration%1000}ms`;
    }
    if(duration < 1000) {
        result += `${duration}ms`;
    }
    return result;
}

3. DOM相关

/**
 * @desc 获取DOM元素的兄弟元素
 * @author qiuer
 * @param {DOM} elem 参数
 * @param {String} siblingClassName 兄弟节点的 class
 * @param classList
 * @returns   {null}    [没有返回]
 */
function siblingElems(elem, siblingClassName) {
    var nodes = [];
    var _elem = elem;
    while ((elem = elem.previousSibling)) {
        if (elem.nodeType == 1 && siblingClassName && domNodeToArray(elem.classList).indexOf(siblingClassName) > -1) {
            nodes.push(elem);
        } else if (elem.nodeType == 1 && !siblingClassName) {
            nodes.push(elem);
        }
    }
    var elem = _elem;
    while ((elem = elem.nextSibling)) {
        if (elem.nodeType == 1 && siblingClassName && domNodeToArray(elem.classList).indexOf(siblingClassName) > -1) {
            nodes.push(elem);
        } else if (elem.nodeType == 1 && !siblingClassName) {
            nodes.push(elem);
        }
    }
    return nodes;
}
/**
 * @desc 获取元素的指定classname 的子节点
 * @author qiuer
 * @param {DOM} pNode 参数
 * @param {String} childClassName 参数
 * @returns   {null}    [没有返回]
 */
function getChildNode(pNode, childClassName) {
    // 如果父节点parentNode含有指定类名childName,这个节点就是目标节点
    if (pNode.className.search(childClassName) !== -1) {
        return [pNode];
    }
    var nodes = pNode.childNodes;
    //将子节点的list转换成标准数组并且过滤掉Text元素
    nodes = domNodeToArray(nodes).filter(function (item) {
        if (item.nodeType !== 3) {
            return item;
        }
    });
    // 如果子节点数组中有值,则递归查找
    if (nodes.length) {
        nodes = nodes.filter(function (item) {
            if (item.className.search(childClassName) !== -1) {
                return item
            }
        });
    } return nodes;
}
/**
 * @desc Javascript-DOM中NodeList对象转数组的通用方法
 * @author qiuer
 * @param {DOM} pNode 参数
 * @param {String} childClassName 参数
 * @returns   {null}    [没有返回]
 */
function domNodeToArray(nodes) {
    var array = null;
    try {
        array = Array.prototype.slice.call(elem.classList, 0); // 针对非IE
    } catch (error) {
        array = new Array();
        for (var i = 0, len = nodes.length; i < len; i++) {
            array.push(nodes[i]);
        }
    }
    return array;
}

4. 随机 相关

// 生成[n,m]范围随机数
// Math.random() 产生一个[0,1)之间的随机数
export const getRandomNum = (n,m) => {
  let result = Math.random()*(m+1-n)+n;
  while(result>m) {
    result = Math.random()*(m+1-n)+n;
  }
  return result;
}
// 生成指定长度的随机中文字符串
export const createRandomCn = (count) => {
  const start = parseInt('4e00', 16)
  const end = parseInt('9fa5', 16)
  let name = ''
  for(let i = 0; i < count; i++) {
      const cha = Math.floor(Math.random() * (end - start))
      name += '\\u' + (start + cha).toString(16)
  }
  return eval(`'${name}'`)
}
// 生成指定长度随机英文字符串
export const getRandomEnStr = (count) => {
  let str = '';
  let arr = ['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'];
  for(const i=0; i<count; i++){
    pos = Math.round(Math.random() * (arr.length-1));
    str += arr[pos];
  }
  return str;
}