总结项目里最常用的JS方法

104 阅读1分钟

文字格式化超过显示...,悬浮显示

function wideCellStyle(value, row, index) {
    return {
        css: {
            "white-space": 'nowrap',
            "text-overflow": 'ellipsis',
            "overflow": 'hidden',
        }
    }
}

精确小数 例如(1.69,1) =>1.7

function RoundNum (num, decimal){ Math.round(num * 10 ** decimal) / 10 ** decimal }

转百万字符串成数字格式的

function wideCellStyle(value, row, index) { 
    value = parseFloat(value);
    let v = value*1000000;
    v = v.toLocaleString('en', { style: 'currency', currency: 'USD'});
    console.log(v);
}

设置光标位置

function setCaretToPos(input,selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    } else if (input.createTextRange) {
        let range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

时间戳转换成yyyy-mm-dd hh:mm:ss @return 符合要求的日期字符串

function getDateTimeStampDate(timeStamp) {
    if (!timeStamp) {
        return null;
    } else {
        let date = new Date(timeStamp)
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        m = m < 10 ? ('0' + m) : m
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        let currentdate = y + '-' + m + '-' + d;
        let hh = date.getHours()
        hh = hh < 10 ? ('0' + hh) : hh
        let mm = date.getMinutes()
        mm = mm < 10 ? ('0' + mm) : mm
        let ss = date.getSeconds()
        ss = ss < 10 ? ('0' + ss) : ss
        let time = hh + ':' + mm + ':' + ss;
        return currentdate + " " + time
    }
}

转换日期对象为日期字符串 (isFull 为true时, 格式如"2000-03-05 01:05:04" 为false时, 格式如"2000-03-05")

function getSmpFormatDate(date, isFull) {
    let pattern = "";
    if (isFull === true || isFull === undefined) {
        pattern = "yyyy-MM-dd hh:mm:ss";
    } else {
        pattern = "yyyy-MM-dd";
    }
    return getFormatDate(date, pattern);
}

前端搜索获取查询结果(适合数量较少的查询)

function getSearchResult(value,propName,searchList){
 let result = searchList.filter(item => item[propName].match(value));
}

验证非法数据,包含非法字符返回true(m:Multiline即多行匹配模式)

function containSpecialCharacters(value) {
   let regEn = /[`#$^*+"']/im; 
   if(regEn.test(value)) {
      toastr.error('Invalid Character, please remove `#$^*+"'', 'Error');
      return true;
   }
}

创建uuid

function createUIID() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    let uuid = s.join("");
    return uuid;
}

第一次总结用到的小方法, 接下来会把学习的Pinia的东西总结一下,求赞鼓励一下下 来自前端小透明~~