项目中常用的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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
*判断undefined返回空字符串
*/
function formatundefined(str) {
if (str == null || str == undefined || str == "undefined") {
return ""
}
return str
}

/**
* 防抖
* @param fn 方法
* @param delay 时间
* @returns {(function(...[*]): void)|*}
*
* demo ===> debounce(fn, 1000)
*/
export const debounce = (fn, delay) => {
let timer

return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}

/**
* 节流
* @param fn 方法
* @param delay 时间
* @returns {(function(...[*]): void)|*}
*
* demo ===> throttle(fn,1000)
*/
export const throttle = (fn, delay) => {
let last = 0 // 上次触发时间

return (...args) => {
const now = Date.now()

if (now - last > delay) {
last = now
fn.apply(this, args)
}
}
}

/**
* 深拷贝
* @param obj
* @param cache
* @returns {Date|RegExp|any}
*
* demo ===>
* let obj = { name: 'Jack', address: { x: 100, y: 200 } };
* deepClone(obj)
*/
export const deepClone = (obj, cache = new WeakMap()) => {
if (typeof obj !== "object") return obj // 普通类型,直接返回
if (obj === null) return obj
if (cache.get(obj)) return cache.get(obj) // 防止循环引用,程序进入死循环
if (obj instanceof Date) return new Date(obj)
if (obj instanceof RegExp) return new RegExp(obj)

// 找到所属原型上的constructor,所属原型上的constructor指向当前对象的构造函数
const cloneObj = new obj.constructor()

cache.set(obj, cloneObj) // 缓存拷贝的对象,用于处理循环引用的情况
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
}
}
return cloneObj
}

/**
* 冒泡排序
* @param arr
* @returns {*}
*
* demo ===>
* bubbleSort([3,1,2,5,8,6])
* bubbleSort(['b','c','a','e','d'])
*/
export const bubbleSort = (arr) => {
const len = arr.length

for (let i = 0; i < len - 1; i += 1) {
// 从第一个元素开始,比较相邻的两个元素,前者大就交换位置
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
const num = arr[j]

arr[j] = arr[j + 1]
arr[j + 1] = num
}
}
}
return arr
}

/**
* 数组去重
* @param arr
* @returns {[]}
*
* demo ===>
* resetArr([1,2,2,2,3,4,5,6])
* resetArr(['b','b','c','a','e','d'])
*/
export const resetArr = (arr) => {
const res = []

arr.forEach((item) => {
if (res.indexOf(item) === -1) {
res.push(item)
}
})
return res
}

/**
* 获取URL参数
* @param type URL类型 1:不加密 2:加密
* @returns {{[p: string]: string}}
*
* demo ===>
* https://www.google.com?id=123&age=30
* urlSearchParams(1) // {id: "123",name: "30"}
*
* https://www.google.com?user=%E9%98%BF%E9%A3%9E&age=16
* urlSearchParams(2) // {user: '阿飞', age: '16'}
*/
export const urlSearchParams = (type = 1) => {
if (type === 1) {
// 创建一个URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search)

// 把键值对列表转换为一个对象
return Object.fromEntries(urlSearchParams.entries())
}
const res = {},
url = window.location.href

if (url.includes("?")) {
const str = url.split("?")[1],
arr = str.split("&")

arr.forEach((item) => {
const key = item.split("=")[0],
val = item.split("=")[1]

res[key] = decodeURIComponent(val) // 解码
})
}
return res
}

/**
* 判断字符串是以什么结尾
* @param str abc123
* @param target 123
* @returns {boolean}
*/
export const confirmEnding = (str, target) => {
// 请把你的代码写在这里
var start = str.length - target.length
var arr = str.substr(start, target.length)
if (arr === target) {
return true
}
return false
}

/**
* 随机数范围
* @param min
* @param max
* @returns {null|number}
*/
export const random = (min, max) => {
if (arguments.length === 1) {
return Math.floor(min + Math.random() * (max + 1 - min))
} else {
return null
}
}

/**
* 四舍五入
* @param n 数
* @param decimals 小数点后第几位
* @returns {number}
*/
export const round = (n, decimals = 0) => {
return Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
}

/**
* 通过key来获取html?后面的数据
* */
function getUrlParam(key) {
var url = decodeURI(location.search.replace(/^\?/, "")).split("&")
var paramsObj = {}
for (var i = 0, iLen = url.length; i < iLen; i++) {
var param = url[i].split("=")
paramsObj[param[0]] = param[1]
}
if (key) {
return paramsObj[key] || ""
}
return paramsObj
}

/**
* 判断数据类型
*/
var toString = Object.prototype.toString
function type(elem) {
if (elem == null) {
return elem + ""
}
return toString
.call(elem)
.replace(/[\[\]]/g, "")
.split(" ")[1]
.toLowerCase()
}

/**
* 判断数组是否包含元素
* @param arr
* @param obj
* @returns {Boolean}
*/
function contains(arr, obj) {
var i = arr.length
while (i--) {
if (arr[i] == obj) {
return true
}
}
return false
}

/**
* 移除数组里的元素
* @param arr
* @param obj
* @returns {Array}
*/
function remove(arr, obj) {
var i = arr.length
var newarr = new Array()
while (i--) {
if (arr[i] != obj) {
newarr.push(arr[i])
}
}
return newarr
}

/**
* 原生拖拽
*/
function dragEvent(drag, dbody) {
window.getSelection
? window.getSelection().removeAllRanges()
: document.selection.empty()
drag.onmousedown = function (event) {
var event = event || window.event
var pageX =
event.pageX || event.clientX + document.documentElement.scrollLeft
var pageY =
event.pageY || event.clientY + document.documentElement.scrollTop
var bodyX = pageX - dbody.offsetLeft
var bodyY = pageY - dbody.offsetTop
window.getSelection
? window.getSelection().removeAllRanges()
: document.selection.empty()
document.onmousemove = function (event) {
var event = event || window.event
var pageX =
event.pageX || event.clientX + document.documentElement.scrollLeft
var pageY =
event.pageY || event.clientY + document.documentElement.scrollTop
dbody.style.left = pageX - bodyX + "px"
dbody.style.top = pageY - bodyY + "px"
window.getSelection
? window.getSelection().removeAllRanges()
: document.selection.empty()
}
}
document.onmouseup = function () {
document.onmousemove = null
}
}

/**
* 往数组里面增加属性
* @param array
* @param dataType
*/
function addDataType(array, dataType) {
for (var i in array) {
array[i].type = dataType
}
}

/**
* 获取当前日期时间 格式"yyyy-MM-dd HH:MM:SS"
*/
function getNowFormatDate() {
var date = new Date()
var seperator1 = "-"
var seperator2 = ":"
var month = date.getMonth() + 1
var strDate = date.getDate()
if (month >= 1 && month <= 9) {
month = "0" + month
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate
}

var currentdata =
date.getFullYear() +
seperator1 +
month +
seperator1 +
strDate +
" " +
date.getHours() +
seperator2 +
date.getMinutes() +
seperator2 +
date.getSeconds()

return currentdata
}

/**
* 获取当前日期前一个月时间 格式"yyyy-MM-dd HH:MM:SS"
*/
function getLastFormatDate() {
var date = new Date()
date.setMonth(date.getMonth() - 1)
var seperator1 = "-"
var seperator2 = ":"
var year = date.getFullYear()
var month = date.getMonth() + 1
var strDate = date.getDate()
var hours = date.getHours()
var seconds = date.getSeconds()
var minutes = date.getMinutes()
if (month >= 1 && month <= 9) {
month = "0" + month
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate
}

if (hours >= 0 && hours <= 9) {
hours = "0" + hours
}
if (seconds >= 0 && seconds <= 9) {
seconds = "0" + seconds
}
if (minutes >= 0 && minutes <= 9) {
minutes = "0" + minutes
}

var lastdata =
year +
seperator1 +
month +
seperator1 +
strDate +
" " +
hours +
seperator2 +
minutes +
seperator2 +
seconds

return lastdata
}

/**
* 随机生产6位数的数字
*/
function getUUidNum() {
var code = Math.floor(Math.random() * 900000) + 100000
return code
}

/**
* 获取当天日期,获取前n天的日期
*/
function getCurrentDate() {
var d = new Date()
var year = d.getFullYear()
var mon = d.getMonth() + 1
var day = d.getDate()
s =
year +
"-" +
(mon < 10 ? "0" + mon : mon) +
"-" +
(day < 10 ? "0" + day : day)
return s
}

/**
* 获取前n天的日期
*/
function getBeforeDate(n) {
var n = n
var d = new Date()
var year = d.getFullYear()
var mon = d.getMonth() + 1
var day = d.getDate()
if (day <= n) {
if (mon > 1) {
mon = mon - 1
} else {
year = year - 1
mon = 12
}
}
d.setDate(d.getDate() - n)
year = d.getFullYear()
mon = d.getMonth() + 1
day = d.getDate()
s =
year +
"-" +
(mon < 10 ? "0" + mon : mon) +
"-" +
(day < 10 ? "0" + day : day)
return s
}