前言:工作的过程中总结的干货,必备的JavaScript代码片段,会持续更新哦。。。
- random()
/*
* @name: random
* @description: 产生随机整数,包含下限值,包括上限值
* @param {Number} lower 下限
* @param {Number} upper 上限
* @return {Number} 返回在下限到上限之间的一个随机整数
*/
export function random(lower, upper) {
return Math.floor(Math.random() * (upper - lower+1)) + lower;
}
- randomColor()
/*
* @name: randomColor
* 产生一个随机的rgb颜色
* @return {String} 返回颜色rgb值字符串内容,如:rgb(201, 57, 96)
*/
export function randomColor() {
// 随机生成 rgb 值,每个颜色值在 0 - 255 之间
var r = random(0, 256),
g = random(0, 256),
b = random(0, 256);
// 连接字符串的结果
var result = "rgb("+ r +","+ g +","+ b +")";
// 返回结果
return result;
}
- getFormatCode()
/*
* @name: getFormatCode
* @description: 根据Value格式化为带有换行、空格格式的HTML代码
* @param: strValue {String} 需要转换的值
* @return: {String}转换后的HTML代码
* @example getFormatCode("测\r\n\s试") => “测<br/> 试”
*/
export function getFormatCode(strValue) {
return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ')
}
- removal()
/*
* @name: removal
* @description: 数组中是对象,根据key去重
* @param: arr {Array} 需要去重的数组
* key {Array} 唯一的字段
* @return: {Array} 去重后的代码
* @example:removal([{id: 1}, {id: 2}, {id: 1}], "id") => [{id: 1}, {id: 2}]
*/
export function removal(arr, key) {
let hash = {};
arr = arr.reduce((preVal, curVal) => {
hash[curVal[key]] ? '' : hash[curVal[key]] = true && preVal.push(curVal);
return preVal
}, [])
}
- methodGetByteLen()
/*
* @name: methodGetByteLen
* @description: 超出多少个字(中文1个,2个英文算1个)显示省略号
* @param: str {String} 需要转换的字符串
* num {Number} 超出多少个
* @return: {String} 去重后的代码
* @example:removal('哈haha哈哈哈', 2) => '哈ha...'
*/
export function methodGetByteLen(str, len) {
let status = true
if (!str) return ['-', status]
let templen = 0
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) {
templen += 2
} else {
templen++
}
if (templen >= len) {
status = false
return [str.substring(0, i) + '...', status]
}
}
return [str, status]
}
- getFloatStr()
/*
* @name: getFloatStr
* @description: 数字自动补全并保留2位小数,将传入数据转换为字符串,并清除字符串中非数字与.的字符,按数字格式补全字符串
* @param:num {String,Number} 需要转换的值
* @return: {String} 转换后数字
* @example: getFloatStr("123.1") => 123.10
*/
export function getFloatStr(value) {
if (isNaN(value)) {
return value
} else {
var value = Math.round(parseFloat(value) * 100) / 100
var xsd = value.toString().split('.')
if (xsd.length == 1) {
value = value.toString() + '.00'
return value.toString()
}
if (xsd.length > 1) {
if (xsd[1].length < 2) {
value = value.toString() + '0'
}
return value.toString()
}
}
}
- milliFormat()
/*
* @name: milliFormat
* @description: 千位符并保留2位小数,将传入数据转换为字符串,并清除字符串中非数字与.的字符,按数字格式补全字符串
* @param: {Number,String} 需要转换的值
* @return: {String} 转换后数字
* @example: milliFormat("1023.1") => 1,023.10
*/
export function milliFormat(s) {
s = String(s)
s = s.replace(/^(\d*)$/, '$1.')
s = (s + '00').replace(/(\d*\.\d\d)\d*/, '$1')
s = s.replace('.', ',')
var re = /(\d)(\d{3},)/
while (re.test(s)) {
s = s.replace(re, '$1,$2')
}
s = s.replace(/,(\d\d)$/, '.$1')
return s.replace(/^\./, '0.')
}
- commafyback()
/*
* @name: commafyback
* @description: 去千位符
* @param: str {String} 需要转换的值
* @return: {String} 转换后数字
* @example: commafyback("102,123.18") => 102123.18
*/
export function commafyback(str) {
var x = String(str).split(',')
return x.join('')
}
- timestampToTime()
/*
* @name: timestampToTime
* @description: 时间戳转化日期格式
* @param:timestamp {Number} 时间戳
* flag {Boolean} 默认值true,时间戳为10位传true,时间戳为13位传flase
* @return: {String} 转换后数字
* @example: timestampToTime(1403058804) => 2014-06-18 10:33:24
*/
export function timestampToTime(timestamp, flag=true) {
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
let date = flag ? new Date(timestamp * 1000) : new Date(timestamp);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
return Y+M+D+h+m+s;
}
10.手机号正则
export const validatePhone = (rule, value, callback) => {
if (value) {
if (!/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/.test(value)) {
return callback(new Error('请输入正确手机号'));
} else {
callback();
}
} else {
callback(new Error('请输入手机号'));
}
}
11.计算两个日期相差天数
/*
* @name: dateDiff
* @description: 计算两个日期相差天数
* @param:eDate {String} 结束时间
* sDate {String} 开始时间
* splitStr {String} 默认值'-',如(2010-10-10的分隔符为“-”)这里是为了通用各种分隔符的日期格式
* @return: {Number} 天数
* @example: dateDiff('2020-08-03', '2020-08-01', '-') => 2
*/
export const dateDiff = (eDate, sDate, splitStr="-") => {
let aDate, oDate1, oDate2, iDays;
aDate = eDate.split(splitStr);
oDate1 = new Date(aDate[1] + splitStr + aDate[2] + splitStr + aDate[0]); //转换为08-03-2020格式
aDate = sDate.split(splitStr);
oDate2 = new Date(aDate[1] + splitStr + aDate[2] + splitStr + aDate[0]);
iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
return iDays;
}
12.获取当前日期的前几天日期
/*
* @name: getOtherDay
* @description: 获取当前日期的前几天日期
* @param:num {String} 前几天
* @return: {Number} 天数
* @example: getOtherDay('1') => 2020-08-02
*/
export const getOtherDay = (num) => {
let date1 = new Date(),
time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
let date2 = new Date(date1);
date2.setDate(date1.getDate()+num);
let time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
return time2
}
13.获取url中"?"后的参数
/*
* @name: getRequest
* @description: 获取url中"?"后的参数
* @return: {Object} 对象
* @example: getRequest('http://localhost:9999?userCode=123') => {userCode: '123'}
*/
export const getRequest = () => {
let url = location.search // 获取url中"?"符后的字串
let theRequest = {}
if (url.indexOf('?') !== -1) {
let str = url.substr(1)
let strs = str.split('&')
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = (strs[i].split('=')[1])
}
}
return theRequest
}
14.手机号中间4位脱敏处理
/*
* @name: desensitizationPhone
* @description: 手机号中间4位脱敏处理
* @param:phone {String} 手机号
* @return: {String} 脱敏手机号
* @example: desensitizationPhone('13812345678') => '138****5678'
*/
export const desensitizationPhone = (phone) => {
let reg = /(\d{3})\d*(\d{4})/
return phone.replace(reg,'$1****$2')
}
15.根据身份证号自动计算生日, 性别
/*
* @name: calculateIDCardNO
* @description: 根据身份证自动计算生日, 性别
* @param:iden {String} 身份证号
* @return: {Object}
* @example: calculateIDCardNO('身份证号') => {birth: '', gender: '', }
*/
export const calculateIDCardNO = (iden) => {
var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/; //验证身份证号
if(reg.test(iden)){
var birthday = "";
var gender = "";
var perinfo = {};
if (iden.length == 15) {
var org_birthday = iden.substring(6, 12);
var org_gender = iden.substring(14, 15);
birthday = "19" + org_birthday.substring(0, 2) + "-"
+ org_birthday.substring(2, 4) + "-"
+ org_birthday.substring(4, 6);
gender = org_gender % 2 == 1 ? "male" : "female";
} else if (iden.length == 18) {
var org_birthday = iden.substring(6, 14);
var org_gender = iden.substring(16, 17);
birthday = org_birthday.substring(0, 4) + "-"
+ org_birthday.substring(4, 6) + "-"
+ org_birthday.substring(6, 8);
gender = org_gender % 2 == 1 ? "male" : "female";
}
perinfo.birth = birthday;
perinfo.gender = gender;
return perinfo
}else{
console.log('身份证号不正确')
}
}
16.根据出生日期计算年龄
/*
* @name: jsGetAge
* @description: 根据出生日期计算年龄
* @param:strBirthday {String} 出生日期
* @return: {String}
* @example: jsGetAge('2000-01-01') => 21
*/
export const jsGetAge = (strBirthday) => {
let returnAge
let strBirthdayArr=strBirthday.split('-')
let birthYear = strBirthdayArr[0]
let birthMonth = strBirthdayArr[1]
let birthDay = strBirthdayArr[2]
let d = new Date()
let nowYear = d.getFullYear()
let nowMonth = d.getMonth() + 1
let nowDay = d.getDate()
if(nowYear == birthYear){
returnAge = 0;//同年 则为0岁
} else {
let ageDiff = nowYear - birthYear // 年之差
if(ageDiff > 0){
if(nowMonth == birthMonth) {
let dayDiff = nowDay - birthDay // 日之差
if(dayDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
} else {
let monthDiff = nowMonth - birthMonth // 月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
}
} else {
returnAge = -1; // 返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge; // 返回周岁年龄
}
- 动态加载 JS 文件
/*
* @name: loadJS
* @description: 动态加载 JS 文件
* @param:files {Array} 函数数组
* done {function} 回调函数
* @example: loadJS(["test1.js", "test2.js"], () => {
* // 用户的回调逻辑
* });
*/
export const loadJS = (files, done) => {
// 获取head标签
const head = document.getElementsByTagName('head')[0];
Promise.all(files.map(file => {W
return new Promise(resolve => {
// 创建script标签并添加到head
const s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = file;
// 监听load事件,如果加载完成则resolve
s.addEventListener('load', (e) => resolve(), false);
head.appendChild(s);
});
})).then(done); // 所有均完成,执行用户的回调事件
}
loadJS(["test1.js", "test2.js"], () => {
// 用户的回调逻辑
});
- 添加默认值
function double() {
return value *2
}
// 不传的话给一个默认值0
function double(value = 0) {
return value * 2
}
// 用户必须要传一个参数,不传参数就抛出一个错误
const required = () => {
throw new Error("This function requires one parameter.")
}
function double(value = required()) {
return value * 2
}
double(3) // 6
double() // throw Error
- 函数只执行一次
/*
* @name: once
* @description: 函数只执行一次
* @param:fn {function}
*/
export function once (fn) {
// 利用闭包判断函数是否执行过
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
}
- 利用 reduce 进行数据结构的转换
const arr = [
{ classId: "1", name: "张三", age: 16 },
{ classId: "1", name: "李四", age: 15 },
{ classId: "2", name: "王五", age: 16 },
{ classId: "3", name: "赵六", age: 15 },
{ classId: "2", name: "孔七", age: 16 }
];
groupArrayByKey(arr, "classId");
function groupArrayByKey(arr = [], key) {
return arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {})
}
结尾:如果你们有什么值得推荐的常用函数,欢迎在评论中补充,可以收纳在本文中。当然也可以直接使用 lodash 这些比较流行的函数式工具库,在这里仅做学习参考使用。