JS常用工具函数

2,444 阅读2分钟

都是平时工作中的积累, 以后会持续更新

随机字符串

//生成动态不重复的一个16位的唯一标识
function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    }).toUpperCase();
}
//example
let uid = uuid();
//8EC77067-5923-462C-AD69-3009BBE5747D
//生成一个指定位数的随机字符串
function randomAlphaNum(len) {
    var rdmString = '';
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len).toUpperCase();
}
//example
randomAlphaNum(32)
//SCZVF6VEULBQZ8S15650PXZDS3J8KREJ

范围内的随机数

function randNum(minnum, maxnum) {
    return Math.floor(min + Math.random() * ((max+1) - min));
}
//example
randNum(0 ,10)  //生成0-10的随机数

获取值的类型


function getType(params){
    return Object.prototype.toString.call(params);
}
//example
getType([])             //[object Array]
getType(function(){})   //[object Function]
getType({})             //[object Object]
function toType(obj) {
    return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
//example
toType([])             //array
toType(function(){})   //function
toType({})             //object

字符串数字改成标识钱的数字

function replaceMoney(str) {
    return str.replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
}
//example
replaceMoney('1231241234')  //1,231,241,234

将arguments对象转成数组

var argArray = Array.prototype.slice.call(arguments);
//或者ES6:
var argArray = Array.from(arguments)

首字母大写转化

function ucFirst(str) {
	return toType(str) === 'string' && !!str ? str[0].toUpperCase() + str.substr(1) : str;
}
//example
ucFirst('hello')    //Hello

日期类型转中文大写

Date.prototype.toCNString = function() {
    var cn = ["○", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
        yy = this.getFullYear().toString(),
        mm = this.getMonth() + 1,
        dd = this.getDate();
    result = [];
    for (var i = 0; i < yy.length; i++) {
        result.push(cn[yy.charAt(i)] ? cn[yy.charAt(i)] : yy.charAt(i));
    }
    result.push('年');
    if (mm < 10) {
        result.push(cn[mm]);
    } else if (mm < 20) {
        result.push('十' + cn[mm % 10]);
    }
    result.push('月');
    if (dd < 10) {
        result.push(cn[dd]);
    } else if (dd < 20) {
        result.push('十' + cn[dd % 10]);
    } else if (dd < 30) {
        result.push('二十' + cn[dd % 10]);
    } else {
        result.push('三十' + cn[dd % 10]);
    }
    result.push('日');
    return result.join('');
};
//example
new Date().toCNString(); //二○一八年二月二十八日

评分组件

function getRate(rate){
	return '★★★★★☆☆☆☆☆'.slice(5 - rate, 10 - rate);
}
//example
getRate(2)   //★★☆☆☆

按位非~判断索引存在

// 如果url含有?号,则后面拼上&符号,否则加上?号
url += ~url.indexOf("?") ? "&" : "?";

基偶数判断

const isOdd = num => !!(num & 1)

判断小数是否相等

// 用户输入的是十进制数字,计算机保存的是二进制数。所以计算结果会有偏差,所以我们不应该直接比较非整数,而是取其上限,把误差计算进去。这样一个上限称为 machine epsilon,双精度的标准 epsilon 值是 2^-53 (Math.pow(2, -53))
function equal(x,y) {  
  return Math.abs(x - y) < Number.EPSILON;
}

文件大小格式化

function formatSize(sizi) {
    const unitsHash = 'B,KB,MB,GB'.split(',')
    let index = 0
    while (size > 1024 && index < unitsHash.length) {
        size /= 1024
        index++
    }
    return Math.round(size * 100) / 100 + unitsHash[index]
}