1.防抖函数
<button>点击</button>
function debounce(fn, delay) {
let timer = null
return function () {
let args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(this, args)
}, delay)
}
}
let btn2 = document.querySelector('button')
btn2.addEventListener('click',debounce(function () {
console.log('哈哈哈')
}, 1000)
)
2.节流函数
<button>点击</button>
function throttle(fn, delay) {
let timer = null
return function () {
let args = arguments
if (!timer) {
timer = setTimeout(function () {
fn.apply(this, args)
timer = null
}, delay)
}
}
}
let btn3 = document.querySelector('button')
btn3.addEventListener(
'click',
throttle(function () {
console.log('哈哈哈1111')
}, 1000)
)
3.数据扁平化处理函数
function flat(arr) {
return arr.reduce((prev, curr) => {
return prev.concat(curr)
}, [])
}
let arr = [
[1, 2, 3, 4],
[11, 12, 13]
]
console.log(flat(arr))
4. 编写一个函数,首字母大写转换hello world
function toUpperCase(str) {
return str.replace(/^\w/, (s) => {
return s.toUpperCase()
}
)
}
console.log(toUpperCase('hello world')
5. 已知有字符串 foo=”get-element-by-id”,写一个 function 将其 转化成驼峰表示法”getElementById”(必会)
let foo = 'get-element-by-id';
function camelize (str) {
return str.replace(/-(\w)/g, function (all, letter) {
return letter.toUpperCase();
});
}
console.log(camelize(foo));