技术栈总结-常用函数
gyh 2019-08-20 vue
# 常用函数
# 生成从 minNum 到 maxNum 的随机数
// 生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
return (Math.random() * (maxNum - minNum + 1) + minNum).toFixed(2);
// 或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
}
}
1
2
3
4
5
6
2
3
4
5
6
# js: 获取 url 中的参数
// 获取url中的参数
function getUrlParam(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg) // 匹配目标参数
if (r != null) return unescape(r[2])
return null // 返回参数值
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 防抖和节流
// throttle节流
function throttle(func, wait) {
let lastTime = 0
return (...args) => {
const now = +new Date()
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}
// debounce防抖
function debounce(func, wait) {
let timer = null
return (...args) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
function onScroll() {
console.log('===scroll===')
}
window.onscroll = debounce(onScroll, 1000)
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
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