常用JS函数学习

一份 JS 常用业务函数手册,例如时间格式的处理、用的是哪个手机浏览器,手机号、邮箱的验证,以此来提高你的开发效率

时间格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export function formatDate (oldDate, fmt) { 
let date = new Date()
if (typeof oldDate === 'string' || typeof oldDate === 'number') {
date = new Date(+oldDate)
} else {
date = oldDate
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
// getMonth()返回0~11
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
function padLeftZero (str) {
return ('00' + str).substr(str.length)
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}

使用说明

oldDate 类型可以是 Date,String,Number

fmt为格式化的类型

  • yyyy年MM月dd -> 2019年09月7日
  • hh分mm秒 -> 16分53秒

获取URL中的参数

虽然大部分写框架都用不上,但是有的时候还是要用。

简单实现

1
2
var urlParams = new URLSearchParams('?post=1234&action=edit');
console.log(urlParams.get('action')); // "edit"

复杂实现

1
2
3
4
5
6
7
8
9
10
11
function getUrlParams(param){
// 有赖于浏览器环境, window.location.search 是浏览器函数
// 意思是:设置或返回从问号 (?) 开始的 URL(查询部分)。
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == param){return pair[1];}
}
return(false);
}

手机端判断浏览器类型

1
2
3
4
5
6
7
8
BrowserInfo = { 
isAndroid: Boolean(navigator.userAgent.match(/android/ig)),
isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),
isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),
isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),
isAli: Boolean(navigator.userAgent.match(/AlipayClient/ig)),
isPhone: Boolean(/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent))
}

数组降维

二维数组

reduce

1
2
3
4
5
let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

concat

1
2
let arr = [ [1], [2], [3] ]
arr = Array.prototype.concat.apply([], arr); // [1, 2, 3]

多维数组

ES6

1
2
3
4
5
6
7
8
9
// 默认1
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

复杂递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function deepClone(obj) { 
function isClass(o) {
if (o === null) return "Null";
if (o === undefined) return "Undefined";
return Object.prototype.toString.call(o).slice(8, -1);
}
var result;
var oClass = isClass(obj);
if (oClass === "Object") {
result = {};
} else if (oClass === "Array") {
result = [];
} else {
return obj;
}
for (var key in obj) {
var copy = obj[key];
if (isClass(copy) == "Object") {
result[key] = deepClone(copy);//递归调用
} else if (isClass(copy) == "Array") {
result[key] = deepClone(copy);
} else {
result[key] = obj[key];
}
}
return result;
}

简单处理

1
2
3
function deepClone() {
return JSON.parse(JSON.stringify(obj))
}

防抖 & 节流

业务中比较多见的场合也就是搜索内容改变提示信息

防抖

1
2
3
4
5
6
7
8
9
10
11
12
function debounce(func, wait, ...rest) {
let timeout;
return () => {
let context = this;
let args = rest;
timeout && clearTimeout(timeout);

timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
function throttle(func, wait, ...rest) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = rest;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}

用对象代替switch/if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

公共内容:
let a = 'VIP'
场景 1
if (a === 'VIP') {
return 1
} else if (a === 'SVIP') {
return 2
}
场景 2
switch(a) {
case 'VIP'
return 1
break
case 'SVIP'
return 2
break
}
场景 3
let obj = {
VIP: 1,
SVIP: 2
}
-------------要说再见啦感谢大佬的光临~-------------