avatar

一些通用方法整理

工具库

https://www.lodashjs.com/

auth.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
return Cookies.get(TokenKey)
}

export function setToken(token) {
return Cookies.set(TokenKey, token)
}

export function removeToken() {
return Cookies.remove(TokenKey)
}

scroll-to.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Math.easeInOutQuad = function(t, b, c, d) {
t /= d / 2
if (t < 1) {
return c / 2 * t * t + b
}
t--
return -c / 2 * (t * (t - 2) - 1) + b
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
})()

/**
* Because it's so fucking difficult to detect the scrolling element, just move them all
* @param {number} amount
*/
function move(amount) {
document.documentElement.scrollTop = amount
document.body.parentNode.scrollTop = amount
document.body.scrollTop = amount
}

function position() {
return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}

/**
* @param {number} to
* @param {number} duration
* @param {Function} callback
*/
export function scrollTo(to, duration, callback) {
const start = position()
const change = to - start
const increment = 20
let currentTime = 0
duration = (typeof (duration) === 'undefined') ? 500 : duration
var animateScroll = function() {
// increment the time
currentTime += increment
// find the value with the quadratic in-out easing function
var val = Math.easeInOutQuad(currentTime, start, change, duration)
// move the document.body
move(val)
// do the animation unless its over
if (currentTime < duration) {
requestAnimFrame(animateScroll)
} else {
if (callback && typeof (callback) === 'function') {
// the animation is done so lets callback
callback()
}
}
}
animateScroll()
}

store.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import {
validatenull
} from '@/utils/validate'
import website from '@/utils/website'

const keyName = website.key + '-';
/**
* 存储localStorage
*/
export const setStore = (params = {}) => {
let {
name,
content,
type,
} = params;
name = keyName + name
let obj = {
dataType: typeof (content),
content: content,
type: type,
datetime: new Date().getTime()
}
if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
else window.localStorage.setItem(name, JSON.stringify(obj));
}
/**
* 获取localStorage
*/

export const getStore = (params = {}) => {
let {
name,
debug
} = params;
name = keyName + name
let obj = {},
content;
obj = window.sessionStorage.getItem(name);
if (validatenull(obj)) obj = window.localStorage.getItem(name);
if (validatenull(obj)) return;
try {
obj = JSON.parse(obj);
} catch{
return obj;
}
if (debug) {
return obj;
}
if (obj.dataType == 'string') {
content = obj.content;
} else if (obj.dataType == 'number') {
content = Number(obj.content);
} else if (obj.dataType == 'boolean') {
content = eval(obj.content);
} else if (obj.dataType == 'object') {
content = obj.content;
}
return content;
}
/**
* 删除localStorage
*/
export const removeStore = (params = {}) => {
let {
name,
type
} = params;
name = keyName + name
if (type) {
window.sessionStorage.removeItem(name);
} else {
window.localStorage.removeItem(name);
}

}

/**
* 获取全部localStorage
*/
export const getAllStore = (params = {}) => {
let list = [];
let {
type
} = params;
if (type) {
for (let i = 0; i <= window.sessionStorage.length; i++) {
list.push({
name: window.sessionStorage.key(i),
content: getStore({
name: window.sessionStorage.key(i),
type: 'session'
})
})
}
} else {
for (let i = 0; i <= window.localStorage.length; i++) {
list.push({
name: window.localStorage.key(i),
content: getStore({
name: window.localStorage.key(i),
})
})

}
}
return list;

}

/**
* 清空全部localStorage
*/
export const clearStore = (params = {}) => {
let { type } = params;
if (type) {
window.sessionStorage.clear();
} else {
window.localStorage.clear()
}

}

validate.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}

/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}

/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}

/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}

/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}

/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}

/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}

/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str === 'string' || str instanceof String) {
return true
}
return false
}

/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg)
}

/**
* 判断是否为空
*/
export function validatenull (val) {
if (typeof val === 'boolean') {
return false
}
if (typeof val === 'number') {
return false
}
if (val instanceof Array) {
if (val.length == 0) return true
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true
} else {
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true
return false
}
return false
}

util.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {validatenull} from './validate'
import request from '@/utils/request'
import * as CryptoJS from'crypto-js'

// 表单序列化
export const serialize = data => {
let list = []
Object.keys(data).forEach(ele => {
list.push(`${ele}=${data[ele]}`)
})
return list.join('&')
}
export const getObjType = obj => {
var toString = Object.prototype.toString
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}
/**
* 对象深拷贝
*/
export const deepClone = data => {
var type = getObjType(data)
var obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
// 不再具有下一层次
return data
}
if (type === 'array') {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (var key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}
/**
* 判断路由是否相等
*/
export const diff = (obj1, obj2) => {
delete obj1.close
var o1 = obj1 instanceof Object
var o2 = obj2 instanceof Object
if (!o1 || !o2) { /* 判断不是对象 */
return obj1 === obj2
}

if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
// Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
}

for (var attr in obj1) {
var t1 = obj1[attr] instanceof Object
var t2 = obj2[attr] instanceof Object
if (t1 && t2) {
return diff(obj1[attr], obj2[attr])
} else if (obj1[attr] !== obj2[attr]) {
return false
}
}
return true
}
/**
* 设置灰度模式
*/
export const toggleGrayMode = (status) => {
if (status) {
document.body.className = document.body.className + ' grayMode'
} else {
document.body.className = document.body.className.replace(' grayMode', '')
}
}
/**
* 设置主题
*/
export const setTheme = (name) => {
document.body.className = name
}

/**
*加密处理
*/
export const encryption = (params) => {
let {
data,
type,
param,
key
} = params
const result = JSON.parse(JSON.stringify(data))
if (type === 'Base64') {
param.forEach(ele => {
result[ele] = btoa(result[ele])
})
} else {
param.forEach(ele => {
var data = result[ele]
key = CryptoJS.enc.Latin1.parse(key)
var iv = key
// 加密
var encrypted = CryptoJS.AES.encrypt(
data,
key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
})
result[ele] = encrypted.toString()
})
}
return result
}

/**
* 浏览器判断是否全屏
*/
export const fullscreenToggel = () => {
if (fullscreenEnable()) {
exitFullScreen();
} else {
reqFullScreen();
}
};
/**
* esc监听全屏
*/
export const listenfullscreen = (callback) => {
function listen() {
callback()
}
document.addEventListener("fullscreenchange", function () {
listen();
});
document.addEventListener("mozfullscreenchange", function () {
listen();
});
document.addEventListener("webkitfullscreenchange", function () {
listen();
});
document.addEventListener("msfullscreenchange", function () {
listen();
});
};
/**
* 浏览器判断是否全屏
*/
export const fullscreenEnable = () => {
return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
}

/**
* 浏览器全屏
*/
export const reqFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
}
};
/**
* 浏览器退出全屏
*/
export const exitFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.exitFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.webkitCancelFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.mozCancelFullScreen();
}
};
/**
* 递归寻找子类的父类
*/

export const findParent = (menu, id) => {
for (let i = 0; i < menu.length; i++) {
if (menu[i].children.length != 0) {
for (let j = 0; j < menu[i].children.length; j++) {
if (menu[i].children[j].id == id) {
return menu[i]
} else {
if (menu[i].children[j].children.length != 0) {
return findParent(menu[i].children[j].children, id)
}
}
}
}
}
}

/**
* 动态插入css
*/

export const loadStyle = url => {
const link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = url
const head = document.getElementsByTagName('head')[0]
head.appendChild(link)
}
/**
* 判断路由是否相等
*/
export const isObjectValueEqual = (a, b) => {
let result = true
Object.keys(a).forEach(ele => {
const type = typeof (a[ele])
if (type === 'string' && a[ele] !== b[ele]) result = false
else if (type === 'object' && JSON.stringify(a[ele]) !== JSON.stringify(b[ele])) result = false
})
return result
}
/**
* 根据字典的value显示label
*/
export const findByvalue = (dic, value) => {
let result = ''
if (validatenull(dic)) return value
if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') {
let index = 0
index = findArray(dic, value)
if (index != -1) {
result = dic[index].label
} else {
result = value
}
} else if (value instanceof Array) {
result = []
let index = 0
value.forEach(ele => {
index = findArray(dic, ele)
if (index != -1) {
result.push(dic[index].label)
} else {
result.push(value)
}
})
result = result.toString()
}
return result
}
/**
* 根据字典的value查找对应的index
*/
export const findArray = (dic, value) => {
for (let i = 0; i < dic.length; i++) {
if (dic[i].value == value) {
return i
}
}
return -1
}
/**
* 生成随机len位数字
*/
export const randomLenNum = (len, date) => {
let random = ''
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
if (date) random = random + Date.now()
return random
}

ruoyi.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {validatenull} from './validate'
import request from '@/utils/request'
import * as CryptoJS from'crypto-js'

// 表单序列化
export const serialize = data => {
let list = []
Object.keys(data).forEach(ele => {
list.push(`${ele}=${data[ele]}`)
})
return list.join('&')
}
export const getObjType = obj => {
var toString = Object.prototype.toString
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}
/**
* 对象深拷贝
*/
export const deepClone = data => {
var type = getObjType(data)
var obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
// 不再具有下一层次
return data
}
if (type === 'array') {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (var key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}
/**
* 判断路由是否相等
*/
export const diff = (obj1, obj2) => {
delete obj1.close
var o1 = obj1 instanceof Object
var o2 = obj2 instanceof Object
if (!o1 || !o2) { /* 判断不是对象 */
return obj1 === obj2
}

if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
// Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
}

for (var attr in obj1) {
var t1 = obj1[attr] instanceof Object
var t2 = obj2[attr] instanceof Object
if (t1 && t2) {
return diff(obj1[attr], obj2[attr])
} else if (obj1[attr] !== obj2[attr]) {
return false
}
}
return true
}
/**
* 设置灰度模式
*/
export const toggleGrayMode = (status) => {
if (status) {
document.body.className = document.body.className + ' grayMode'
} else {
document.body.className = document.body.className.replace(' grayMode', '')
}
}
/**
* 设置主题
*/
export const setTheme = (name) => {
document.body.className = name
}

/**
*加密处理
*/
export const encryption = (params) => {
let {
data,
type,
param,
key
} = params
const result = JSON.parse(JSON.stringify(data))
if (type === 'Base64') {
param.forEach(ele => {
result[ele] = btoa(result[ele])
})
} else {
param.forEach(ele => {
var data = result[ele]
key = CryptoJS.enc.Latin1.parse(key)
var iv = key
// 加密
var encrypted = CryptoJS.AES.encrypt(
data,
key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
})
result[ele] = encrypted.toString()
})
}
return result
}

/**
* 浏览器判断是否全屏
*/
export const fullscreenToggel = () => {
if (fullscreenEnable()) {
exitFullScreen();
} else {
reqFullScreen();
}
};
/**
* esc监听全屏
*/
export const listenfullscreen = (callback) => {
function listen() {
callback()
}
document.addEventListener("fullscreenchange", function () {
listen();
});
document.addEventListener("mozfullscreenchange", function () {
listen();
});
document.addEventListener("webkitfullscreenchange", function () {
listen();
});
document.addEventListener("msfullscreenchange", function () {
listen();
});
};
/**
* 浏览器判断是否全屏
*/
export const fullscreenEnable = () => {
return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
}

/**
* 浏览器全屏
*/
export const reqFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
}
};
/**
* 浏览器退出全屏
*/
export const exitFullScreen = () => {
if (document.documentElement.requestFullScreen) {
document.exitFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.webkitCancelFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.mozCancelFullScreen();
}
};
/**
* 递归寻找子类的父类
*/

export const findParent = (menu, id) => {
for (let i = 0; i < menu.length; i++) {
if (menu[i].children.length != 0) {
for (let j = 0; j < menu[i].children.length; j++) {
if (menu[i].children[j].id == id) {
return menu[i]
} else {
if (menu[i].children[j].children.length != 0) {
return findParent(menu[i].children[j].children, id)
}
}
}
}
}
}

/**
* 动态插入css
*/

export const loadStyle = url => {
const link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = url
const head = document.getElementsByTagName('head')[0]
head.appendChild(link)
}
/**
* 判断路由是否相等
*/
export const isObjectValueEqual = (a, b) => {
let result = true
Object.keys(a).forEach(ele => {
const type = typeof (a[ele])
if (type === 'string' && a[ele] !== b[ele]) result = false
else if (type === 'object' && JSON.stringify(a[ele]) !== JSON.stringify(b[ele])) result = false
})
return result
}
/**
* 根据字典的value显示label
*/
export const findByvalue = (dic, value) => {
let result = ''
if (validatenull(dic)) return value
if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') {
let index = 0
index = findArray(dic, value)
if (index != -1) {
result = dic[index].label
} else {
result = value
}
} else if (value instanceof Array) {
result = []
let index = 0
value.forEach(ele => {
index = findArray(dic, ele)
if (index != -1) {
result.push(dic[index].label)
} else {
result.push(value)
}
})
result = result.toString()
}
return result
}
/**
* 根据字典的value查找对应的index
*/
export const findArray = (dic, value) => {
for (let i = 0; i < dic.length; i++) {
if (dic[i].value == value) {
return i
}
}
return -1
}
/**
* 生成随机len位数字
*/
export const randomLenNum = (len, date) => {
let random = ''
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
if (date) random = random + Date.now()
return random
}

tools.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400


/**
* @description 通用正则
*/
export const regexp = {
email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
url: /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i,
number: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
isZipCode: /^[0-9]{6}$/,
phone: /^((0\d{2,3}-\d{7,8})|(0\d{2,3}-\d{7,8}#\d{3,7})|(\d{7,8})|(\d{7,8}#\d{3,7})|((13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}))$/,
idCard: /^\d{15}(\d{2}[A-Za-z0-9])?$/,
isAccount: /^\w+$/, // 字母下划线数字
integer: /^([1-9]\d*|[0]{1,1})$/, // 0开头的正整数
isUppercaseLetter: /^[A-Z]+$/, // 大写字母
isUppercaseLetterAndNumber: /^[A-Z][A-Z0-9]*$/, // 大写字母开头,包含大写字母与数字
isUppercaseLetterAndNumberStr: /^[A-Z][A-Z0-9\-/]*$/ // 大写字母开头,包含大写字母与数字
};

/**
* @param {*} date date日期
* @param {*} addMonth 月份
* @param {*} hms 是否显示时分秒
* @description Date对象转化成YYYY - MM - DD格式, addMonth获取给点日期指定月份后或者前的日期,hms是否显示时分秒
*/
export const formatDate = (date, addMonth, hms = 1) => {
if (date === null) return "";
let d = new Date(date);
if (addMonth) {
d.setMonth(d.getMonth() + addMonth);
}
let year = d.getFullYear();
let month =
d.getMonth() + 1 >= 10 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
let day = d.getDate() >= 10 ? d.getDate() : "0" + d.getDate();
let hours = d.getHours() >= 10 ? d.getHours() : "0" + d.getHours();
let min = d.getMinutes() >= 10 ? d.getMinutes() : "0" + d.getMinutes();
let second = d.getSeconds() >= 10 ? d.getSeconds() : "0" + d.getSeconds();
if (addMonth)
day = d.getDate() >= 10 ? d.getDate() - 1 : "0" + (d.getDate() - 1);
if (!hms) return `${year}-${month}-${day}`;
return `${year}-${month}-${day} ${hours}:${min}:${second}`;
};

export const forEach = (arr, fn) => {
if (!arr.length || !fn) return;
let i = -1;
let len = arr.length;
while (++i < len) {
let item = arr[i];
fn(item, i, arr);
}
};

/**
* @param {Array} arr1
* @param {Array} arr2
* @description 得到两个数组的交集, 两个数组的元素为数值或字符串
*/
export const getIntersection = (arr1, arr2) => {
let len = Math.min(arr1.length, arr2.length);
let i = -1;
let res = [];
while (++i < len) {
const item = arr2[i];
if (arr1.indexOf(item) > -1) res.push(item);
}
return res;
};

/**
* @param {Array} arr1
* @param {Array} arr2
* @description 得到两个数组的并集, 两个数组的元素为数值或字符串
*/
export const getUnion = (arr1, arr2) => {
return Array.from(new Set([...arr1, ...arr2]));
};

/**
* @param {Array} target 目标数组
* @param {Array} arr 需要查询的数组
* @description 判断要查询的数组是否至少有一个元素包含在目标数组中
*/
export const hasOneOf = (targetarr, arr) => {
return targetarr.some(_ => arr.indexOf(_) > -1);
};

/**
* @param {String|Number} value 要验证的字符串或数值
* @param {*} validList 用来验证的列表
*/
export function oneOf(value, validList) {
for (let i = 0; i < validList.length; i++) {
if (value === validList[i]) {
return true;
}
}
return false;
}

/**
* @param {Number} timeStamp 判断时间戳格式是否是毫秒
* @returns {Boolean}
*/
const isMillisecond = timeStamp => {
const timeStr = String(timeStamp);
return timeStr.length > 10;
};

/**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} currentTime 当前时间时间戳
* @returns {Boolean} 传入的时间戳是否早于当前时间戳
*/
const isEarly = (timeStamp, currentTime) => {
return timeStamp < currentTime;
};

/**
* @param {Number} num 数值
* @returns {String} 处理后的字符串
* @description 如果传入的数值小于10,即位数只有1位,则在前面补充0
*/
const getHandledValue = num => {
return num < 10 ? "0" + num : num;
};

/**
* @param {Number} timeStamp 传入的时间戳
* @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间
*/
const getDate = (timeStamp, startType) => {
const d = new Date(timeStamp * 1000);
const year = d.getFullYear();
const month = getHandledValue(d.getMonth() + 1);
const date = getHandledValue(d.getDate());
const hours = getHandledValue(d.getHours());
const minutes = getHandledValue(d.getMinutes());
const second = getHandledValue(d.getSeconds());
let resStr = "";
if (startType === "year")
resStr =
year +
"-" +
month +
"-" +
date +
" " +
hours +
":" +
minutes +
":" +
second;
else resStr = month + "-" + date + " " + hours + ":" + minutes;
return resStr;
};

/**
* @param {String|Number} timeStamp 时间戳
* @returns {String} 相对时间字符串
*/
export const getRelativeTime = timeStamp => {
// 判断当前传入的时间戳是秒格式还是毫秒
const IS_MILLISECOND = isMillisecond(timeStamp);
// 如果是毫秒格式则转为秒格式
if (IS_MILLISECOND) Math.floor((timeStamp /= 1000));
// 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型
timeStamp = Number(timeStamp);
// 获取当前时间时间戳
const currentTime = Math.floor(Date.parse(new Date()) / 1000);
// 判断传入时间戳是否早于当前时间戳
const IS_EARLY = isEarly(timeStamp, currentTime);
// 获取两个时间戳差值
let diff = currentTime - timeStamp;
// 如果IS_EARLY为false则差值取反
if (!IS_EARLY) diff = -diff;
let resStr = "";
const dirStr = IS_EARLY ? "前" : "后";
// 少于等于59秒
if (diff <= 59) resStr = diff + "秒" + dirStr;
// 多于59秒,少于等于59分钟59秒
else if (diff > 59 && diff <= 3599)
resStr = Math.floor(diff / 60) + "分钟" + dirStr;
// 多于59分钟59秒,少于等于23小时59分钟59秒
else if (diff > 3599 && diff <= 86399)
resStr = Math.floor(diff / 3600) + "小时" + dirStr;
// 多于23小时59分钟59秒,少于等于29天59分钟59秒
else if (diff > 86399 && diff <= 2623859)
resStr = Math.floor(diff / 86400) + "天" + dirStr;
// 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前
else if (diff > 2623859 && diff <= 31567859 && IS_EARLY)
resStr = getDate(timeStamp);
else resStr = getDate(timeStamp, "year");
return resStr;
};

/**
* @returns {String} 当前浏览器名称
*/
export const getExplorer = () => {
const ua = window.navigator.userAgent;
const isExplorer = exp => {
return ua.indexOf(exp) > -1;
};
if (isExplorer("MSIE")) return "IE";
else if (isExplorer("Firefox")) return "Firefox";
else if (isExplorer("Chrome")) return "Chrome";
else if (isExplorer("Opera")) return "Opera";
else if (isExplorer("Safari")) return "Safari";
};

/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function() {
if (document.addEventListener) {
return function(element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event && handler) {
element.attachEvent("on" + event, handler);
}
};
}
})();

/**
* @description 解绑事件 off(element, event, handler)
*/
export const off = (function() {
if (document.removeEventListener) {
return function(element, event, handler) {
if (element && event) {
element.removeEventListener(event, handler, false);
}
};
} else {
return function(element, event, handler) {
if (element && event) {
element.detachEvent("on" + event, handler);
}
};
}
})();

/**
* 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性
* 如果没有传入key这个参数,则判断obj对象是否有键值对
*/
export const hasKey = (obj, key) => {
if (key) return key in obj;
else {
let keysArr = Object.keys(obj);
return keysArr.length;
}
};

/**
* @param {*} obj1 对象
* @param {*} obj2 对象
* @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串
*/
export const objEqual = (obj1, obj2) => {
const keysArr1 = Object.keys(obj1);
const keysArr2 = Object.keys(obj2);
if (keysArr1.length !== keysArr2.length) return false;
else if (keysArr1.length === 0 && keysArr2.length === 0) return true;
/* eslint-disable-next-line */ else
return !keysArr1.some(key => obj1[key] != obj2[key]);
};

/**
*
* @param {*} num
* @description 表格的序号
*/
export const sortNumber = num => {
if (num < 10) return `0${num}`;
else return num;
};

var restArguments = function(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0:
return func.call(this, rest);
case 1:
return func.call(this, arguments[0], rest);
case 2:
return func.call(this, arguments[0], arguments[1], rest);
}
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
};

var delay = restArguments(function(func, wait, args) {
return setTimeout(function() {
return func.apply(null, args);
}, wait);
});
/**
*
* @param {*} func
* @param {*} wait
* @param {*} immediate
* @description 函数防抖
* @returns
*/
export const debounce = (func, wait, immediate) => {
var timeout, result;

var later = function(context, args) {
timeout = null;
if (args) result = func.apply(context, args);
};

var debounced = restArguments(function(args) {
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(this, args);
} else {
timeout = delay(later, wait, this, args);
}

return result;
});

debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};

return debounced;
};

/**
* @param {*} data
* @param {*} isFilter
* @description post请求参数encode
* @returns {String}
*/
export const formatData = (data, isFilter) => {
// Do whatever you want to transform the data
let ret = "";
for (let prop in data) {
if (isFilter) {
// 过滤null、undefined、空字符串
if (data[prop] != null && data[prop] != undefined && data[prop] !== "") {
ret += `${ret ? "&" : ""}${encodeURIComponent(
prop
)}=${encodeURIComponent(data[prop])}`;
}
} else {
ret += `${ret ? "&" : ""}${encodeURIComponent(prop)}=${encodeURIComponent(
data[prop]
)}`;
}
}
return ret;
};

/**
* 判断是否为空
*/
export function validatenull (val) {
if (typeof val === 'boolean') {
return false
}
if (typeof val === 'number') {
return false
}
if (val instanceof Array) {
if (val.length == 0) return true
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true
} else {
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true
return false
}
return false
}
文章作者: 张复明
文章链接: https://hexo.zhangaming.com/2021/02/19/js-tool/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿明的博客
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论