JS一些工具函数

type() 判断数据类型,返回字符串

// 数据类型对照列表
var typeList = {
    '[object String]': 'string',
    '[object Boolean]': 'boolean',
    '[object Undefined]': 'undefined',
    '[object Number]': 'number',
    '[object Symbol]': 'Symbol',
    '[object Object]': 'object',
    '[object Error]': 'error',
    '[object Function]': 'function',
    '[object Date]': 'date',
    '[object Math]': 'Math',
    '[object Array]': 'array',
    '[object RegExp]': 'regexp',
    '[object Null]': 'null',
    '[object NodeList]': 'nodeList',
    '[object HTMLCollection]': 'HTMLCollection',
    '[object Arguments]': 'arguments',
    '[object HTMLDocument]': 'document'
};

// 判断数据类型,返回字符串
function type(obj){
    return typeList[Object.prototype.toString.call(obj)] || (obj instanceof Node ? 'node' : '');
}

objectIsNotEmpty() 是对象且不为空,返回布尔值

// 是普通对象,且不为空,返回布尔值
function objectIsNotEmpty(obj){
    return type(obj) === 'object' && JSON.stringify(obj) !== '{}';
}

deepCopy()数据深度拷贝

该方法只针对普通 {} 对象和数组进行深度拷贝

function deepCopy(obj){
 	// 只针对普通{}对象和数组
	if(/^\[object\s(Object|Array)\]$/.test(Object.prototype.toString.call(obj))){
    // 不直接定义[]或{}是为了要保留该对象的原型链
        var tempObj = new obj.constructor();
        for(var key in obj){
           	tempObj[key] = deepCopy(obj[key]);
        }
        return tempObj;
    }else{
        return obj;
    }
}

后端Node.js

生成uuid

const uuid = require('uuid');
 
/**
 * @method 返回一个唯一符号
 */
exports.uuid = function(){
    //v1是基于时间戳生成uuid,v4是随机生成uuid
    return uuid.v4().replace(/\-/g, '');
}

md5加盐加密

const crypto = require('crypto');
 
/**
 * @param {string} str 需要加密的字符串
 * @method md5签名加密
 */
exports.md5 = function(str){
    let hash = crypto.createHash('md5');
    let salt = 'xxx';        //加盐
    hash.update(`${str}:${salt}`);
    return hash.digest('hex');      //16进制
}
posted @ 2020-09-07 22:43  samfung09  阅读(147)  评论(0)    收藏  举报